Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

share|improve this question
add comment

1 Answer 1

up vote 6 down vote accepted

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:

share|improve this answer
6  
The "other possibility" won't work. You can't quote a table name. Prepare should only be used for values. –  Andrew Nacin Dec 14 '12 at 7:05
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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