I am receiving this warning when I try to run a database query:

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

The offending query is:

$result = $wpdb->get_var(
    $wpdb->prepare(
        "SELECT DISTINCT meta_value FROM $metatable
        WHERE meta_key LIKE '%matchme%'
        AND meta_value IS NOT NULL
        AND meta_value <> ''" 
    )
);

Is there a way to remove the error by modifying the above query?

1
1

Remove the call to $wpdb->prepare():

$result = $wpdb->get_var(
    "SELECT DISTINCT meta_value FROM $metatable
    WHERE meta_key LIKE '%matchme%'
    AND meta_value IS NOT NULL
    AND meta_value <> ''"
);

In this case, the $wpdb->prepare() function is not doing anything. There are no variables holding unknown values, therefore there is no need to sanitize them.

If you did have variables that need sanitizing, you can add a second argument to the function:

$result = $wpdb->get_var(
    $wpdb->prepare(
        "SELECT DISTINCT meta_value FROM %s
        WHERE meta_key LIKE '%matchme%'
        AND meta_value IS NOT NULL
        AND meta_value <> ''",
    $metatable )
);

Relevant links:

  • PHP Warning: Missing argument 2 for wpdb::prepare()
  • Ticket #22873: Consider moving to a notice for $wpdb->prepare in 3.5.1

Leave a Reply

Your email address will not be published. Required fields are marked *