0

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');
Community
  • 1
  • 1
Swen
  • 767
  • 1
  • 9
  • 31
  • 2
    Take a look http://stackoverflow.com/questions/24988867/when-should-i-use-prepared-statements/24989031 –  Jun 01 '16 at 02:49
  • 2
    Example 2 is precisely why you use prepared statements. Short answer: **YES**. – tadman Jun 01 '16 at 03:06
  • So just to be 100% sure. WordPress's `$wpdb` functions do not automatically prepare SQL statements to prevent SQL Injections? Or is it that some of them do, and others don't? – Swen Jun 01 '16 at 03:52
  • 1
    Technically `$wpdb` is not a function, it's an object made by `wpdb` class. And as far as I know, no it doesn't. You must always sanitize the db query if you are entrusting a user to run it. – dingo_d Jun 01 '16 at 10:59
  • 1
    Also related: [How can I prevent SQL injection in PHP?](https://stackoverflow.com/q/60174/1287812) – brasofilo Jul 21 '18 at 17:28

1 Answers1

2

As I understand - the methods those have placeholders for query parameters ($wpdb->insert(), $wpdb->update(), $wpdb->delete()) don't need the $wpdb->prepare() method, and they are already safe.

But the others - those don't have placeholders, need additional sql escaping.

Leo240
  • 766
  • 7
  • 16