Stackoverflow type of badge plugin giving warnings in WordPress 3.5

Lead developer Nacin answers this one:

Hello plugin or theme author! You possibly found this post after
searching the Internet for the error above: “PHP Warning: Missing
argument 2 for wpdb::prepare().”

So, this is a new warning in 3.5. No sites are broken, everything is
fine as before. But, this is indeed something you need to look at,
because you may be exposing your users to a possible SQL injection
vulnerability. Now that’s no fun!

Have a read of the rest, for further explanation.

As for rehabilitating your existing code:

$wpdb->prepare( 
    "
    SELECT COUNT(*)
    FROM " . $wpdb->prefix . "comments
    WHERE user_id = " . $args['user_ID'] . "
    AND comment_approved = '1'
    " 
)

First, clean it up by getting rid of the unnecessary string concatenation, and calling $wpdb->comments for the comments table:

$wpdb->prepare( 
    "
    SELECT  COUNT(*)
    FROM    $wpdb->comments
    WHERE   user_id = $args['user_ID']
    AND     comment_approved = '1'
    " 
)

Now, the warning has to do with this part of the query:

WHERE   user_id = $args['user_ID']

You need to replace $args['user_ID'] with $d, and then use $args['user_ID'] as the missing, second parameter:

$wpdb->prepare( 
    "
    SELECT  COUNT(*)
    FROM    $wpdb->comments
    WHERE   user_id = %d
    AND     comment_approved = '1'
    ",
    $args['user_ID'] // %d
)

The second one should be similar:

$wpdb->prepare( 
    "
    SELECT    COUNT(*)
    FROM      $wpdb->posts
    WHERE     post_author = %d
    AND       post_status="publish"
    AND       post_type="post"
    ",
    $args['user_ID'] // %d
)

Leave a Comment