When not to prepare database queries in WordPress plugins and themes

You may already know to prepare your SQL queries using $wpdb->prepare but what you may not know is it’s unnesecary if the SQL query doesn’t use any parameters.

In fact, using $wpdb->get_results without any parameters will bring up the following error message in debug mode.

PHP Warning: Missing argument 2 for wpdb::prepare()

In these cases, you can safely pass your SQL query directly to $wpdb->get_results

For example, this is how you would make an SQL query where no parameters are used.

$wpdb->get_results("SELECT * FROM table");

But if you need to pass a parameter, you need to use $wpdb->prepare first. For example,

$sql = $wpdb->prepare( "SELECT * FROM table WHERE ID = %d", $id);
$wpdb->get_results($sql);

More information: