2

I know that we don't need to use prepare($query) when we put it in insert() and update() because these functions sanitize data for us but I'm not sure if we need to prepare query before putting it in get_results(), get_row() and get_var()?

Thank you.

1 Answer 1

4

If your query has no dynamic input, then you technically do not need to use $wpdb->prepare(), however that assumes your own input is safe.

If your query contains parameters in which are dynamic, especially supplied by users from a form as an example, then you will want to use $wpdb->prepare().

Using $wpdb->prepare() is just good practice, but in order to use it, you must pass at least two arguments (the query, and at least one placeholder).

Please note: As of 3.5, wpdb::prepare() enforces a minimum of 2 arguments.

See: https://make.wordpress.org/core/2012/12/12/php-warning-missing-argument-2-for-wpdb-prepare/

6
  • Thank you for the answer. But you please explain to me this. I'm wondering if get_results, get_row, get_var functions do have built-in sanitizing function and we don't need to do extra work to protect the query even it contains dynamic parameters? Or we have to use prepare() all the time with dynamic parameters?
    – Louis Tran
    Commented Feb 16, 2016 at 5:44
  • 1
    Nope, they do not call prepare() internally, like insert() and update() do... It's up to you to sanitize data for methods in question.
    – Adam
    Commented Feb 16, 2016 at 5:52
  • So there are 2 methods right? 1. Sanitize data first => No need prepare(); 2. Use prepare() with raw data. Is this correct?
    – Louis Tran
    Commented Feb 16, 2016 at 6:03
  • You can sanitize before passing data to the likes of a method such as get_results() but that's what prepare() was intended for, doing the sanitization for you. I recommend reading the source for prepare() in wp-includes/wp-db.php around line 1210 to see exactly what this method does under the hood for you.
    – Adam
    Commented Feb 16, 2016 at 6:28
  • You need a minimum of one placeholder - not two - which after the query, becomes the second argument. Review the core comments make.wordpress.org/core/2012/12/12/… . This should be edited so it doesn't mislead.
    – Bob Diego
    Commented May 28, 2017 at 20:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.