I have a hard time figuring out if I should be using $wpdb->prepare
on my database queries in WordPress to prevent things such as SQL injection.
The $wpdb Codex shows some examples using the $wpdb->prepare function, and other examples not using it.
Also, in this answer on StackOverflow, someone mentioned that a function such as $wpdb->insert
has the same level of safety as using $wpdb->prepare
. But what about other $wpdb
functions such as $wpdb->get_var
or $wpdb->query
?
When should I use $wpdb->prepare
, if at all?
Some of my (simplified) $wpdb
class and function usage looks like this:
Example 1: $wpdb->insert
$wpdb->insert(
'special_posts',
array(
'title' => $title,
'selftext_html' => $selftext_html,
'selftext' => $selftext,
),
array(
'%s',
'%s',
'%s',
)
);
Example 2: $wpdb->get_results
$wpdb->get_results("SELECT * FROM special_posts WHERE selftext_html = '$value'");
Example 3: $wpdb->get_var
$wpdb->get_var("SELECT title FROM special_posts ORDER BY id DESC LIMIT 1");
Example 4: $wpdb->query
$wpdb->query('TRUNCATE TABLE special_posts');