Search code examples
phpmysqlmysql-num-rows

mysql_num_rows doesn't work when there are no rows


First off, yes, I know mysql_num_rows() is deprecated.

Now, continuing on to the actual question, I'm making a page where users can post things and other users can like them. But when the post displays, and the user viewing them didn't/hasn't liked the post, the mysql_num_rows() doesn't work.

Here's my code:

<?
$plikes=mysql_query("SELECT * FROM postLikes WHERE username='$myusername' AND postId='$postId'");
$plikesRows=mysql_num_rows($plikes)or die("error: ".mysql_error());
if ($plikesRows>=1) {
//stuff
}
else {
//other stuff
}
?>

the variables $myusername and $postId are set correctly, and I tested the query and it works without any errors. But when I go onto the page, all it displays is a "error:", without any error.


Solution

  • That line of code is not doing what you think it is. mysql_num_rows($plikes) becomes 0 which is type juggled to false so the second half of the OR statement is triggered. This happens because by using OR you turned the results of line of code into a boolean evaluation.

    $plikes=mysql_query("SELECT * FROM postLikes WHERE username='$myusername' AND postId='$postId'");
    if (!mysql_error()) {
        $plikesRows=mysql_num_rows($plikes);
        if ($plikesRows>=1) {
        //stuff
        }
        else {
        //other stuff
        }
    }
    else {
        die("error: ".mysql_error());
    }