$wpdb->prepare() warning in WordPress 3.5

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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 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:


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x