Search code examples
phpmysql-num-rows

Mysql error when counting rows


I have a problem when trying to count the rows in a table.

The variable $username_me equals to the session username. None of them is in an if or else statement.

The error i get is:

Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in /home/*/public_html/**/sidebar.php on line 21

Line 21 is the last line in the code bit i pasted.

//Count unread oneliners
$oneliners_sql = "SELECT * FROM oneliners WHERE to_user='$username_me' AND read=0";
$oneliners_query = mysql_query($oneliners_sql);
$oneliners_num = mysql_num_rows($oneliners_query);

Solution

  • .1. read is mysql reserved word and must be quoted in backticks:

    $sql = "SELECT * FROM oneliners WHERE to_user='$username_me' AND `read`=0";
    

    .2. never use SELECT * to count rows. Use SELECT count(*) instead.

    .3. always run all your queries this way to see any error occurred.

    //Count unread oneliners
    $sql = "SELECT count(*) FROM oneliners WHERE to_user='$username_me' AND `read`=0";
    $result = mysql_query($sql) or trigger_error(mysql_error()." ".$sql);
    $row = mysql_fetch_row($result);
    $oneliners_num = $row[0];
    

    never use die() for this purpose, despite of all these stupid suggestions.

    .4. Create a function for such a usual task.

    function getOne($sql) {
      $result = mysql_query($sql) or trigger_error(mysql_error()." ".$sql);
      if ($row = mysql_fetch_row($result)) {
        return $row[0];
      }
    }
    

    So, you'll be able to get your num with one line

    $oneliners_num = getOne("SELECT count(*) FROM oneliners WHERE to_user='$username_me' AND `read`=0");