Skip to content
Advertisement

Wpdb prepare was called incorrectly

I want to prepare my data to avoid SQL Injections. So my current working code to show a list of data from a table’s column:

global $wpdb;
$sliders = $wpdb->get_results('SELECT alias, title FROM wp_revslider_sliders', ARRAY_A);

echo '<select name="revslider">';
if ($sliders) {
    foreach($sliders as $slide){
        echo '<option value="'.$slide['alias'].'" '.($select_revslider_shortcode == $slide['alias'] ? 'selected=""' : '').'>'.$slide['title'].'</option>';
    }
}
echo '</select>';

I need to use $wpdb->prepare to be sure that my datas are correctly brought from the db. My current progress:

$sliders = $wpdb->query($wpdb->prepare("SELECT id, alias, title FROM wp_revslider_sliders", ARRAY_A));

This isn’t working. I get a notice:

Notice: wpdb::prepare was called incorrectly. The query argument of wpdb::prepare() must have a placeholder.

Can anyone tell me where I’m wrong with my code?

Regards

Advertisement

Answer

The prepare method is used to protect against SQL injection. You’d use it when you want to insert variables into your query. It accepts placeholders such as %s for string, %d for integers and %f for floats.

Your query doesn’t have any variables so you don’t need the prepare method. You’re seeing an error because you aren’t using any placeholders.

https://developer.wordpress.org/reference/classes/wpdb/#protect-queries-against-sql-injection-attacks

5 People found this is helpful
Advertisement