-1

I have this query in my PHP:

<?php
$comments_list = mysql_query("SELECT * FROM comments ORDER BY `date` DESC, `time` DESC LIMIT 5");
echo mysql_error();
if (mysql_num_rows($comments_list) != 0)
{
    echo('<ul>');
    while ($comment = mysql_fetch_array($comments_list))
    {
        echo('<li>'.substr($comment['content'],0,70).'</li>');
    }
    echo('</ul>');
}
else
{
    echo('<center>No comment.</center>');
}
?>

And it gives this error if my table is empty:

Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in C:\Program Files (x86)\EasyPHP-5.3.9\www\admin\index.php on line 101

EDIT: I was querying LIMIT 5 before the ORDER BY. Now it's fixed and I added the echo mysql_error() as edited in the question.

Frederick Marcoux
  • 2,195
  • 1
  • 26
  • 57

2 Answers2

2

You are not doing any error checking in your query. You need to do that after a mysql_query() call, because on a query error, it will return boolean false and your script will break exactly the way you show.

Add error checking to your query. How to do this is outlined in the manual on mysql_query() or in this reference question.

Community
  • 1
  • 1
Pekka
  • 442,112
  • 142
  • 972
  • 1,088
0

Because $comments_list is false, use mysql_error() to see what is wrong.

$comments_list = mysql_query("SELECT * FROM comments LIMIT 5 ORDER BY `date` DESC, `time` DESC");
if (!$comments_list ) {
    die('Invalid query: ' . mysql_error());
}
xdazz
  • 158,678
  • 38
  • 247
  • 274