Fixed a php bug, $wpdb->get_var() – Differentiating between zero & no results

I use a custom made voting plugin for one of my website. It lets users vote a vote up or down.

There’s code in the plugin that checks if voting data already exists for a post or not, if it exists, the code would update that row else it would create a new row.

For posts that had zero votes, the plugin was creating new row each time a user voted.

The code used to check if an entry existed:

Function1

$sql="SELECT `$up_type` FROM `$table_name` WHERE `post_id` = '$post_id' ;";
$to_ret=$wpdb->get_var($sql);
if(empty($to_ret))
{
$to_ret=0;
}
return $to_ret;

For no results and for a post with 0 votes, it would return the value 0.

I created a separate function because the same function was called multiple times, and for some instances I needed it to return 0 value. Anyways, I modified the code.

Function2

$sql="SELECT `$up_type` FROM `$table_name` WHERE `post_id` = '$post_id' ;";
$to_ret=$wpdb->get_var($sql);
if(is_null($to_ret))
{
$to_ret=nothingfound;
}
return $to_ret;

The get_var function returns a single variable from the database. Though only one variable is returned, the entire result of the query is cached for later use. Returns NULL if no result is found.

http://codex.wordpress.org/Class_Reference/wpdb

Permalink

Leave a Comment

Captcha * Time limit is exhausted. Please reload CAPTCHA.

Related Posts