Search code examples
phpmysqlmysql-num-rows

Proper way to ask if mysql_num_rows in PHP


Because mysql_num_rows returns false if there are no rows returned, would it be best to do:

$query = mysql_query("SELECT id FROM table WHERE something = 'this'"); 
$result = mysql_num_rows($query);

if ($result) { }

Or should I do:

if ($result >= 1) { }

Solution

  • The proper one

    $result = mysql_query("SELECT id FROM table WHERE something = 'this'"); 
    if (mysql_num_rows($result)){
        //there are results
    }
    

    however, you could do this easier, without checking

    $result = mysql_query("SELECT id FROM table WHERE something = 'this'"); 
    while($row = mysql_fetch_assoc($result))
        //there are results
    }
    

    Please. Give your variables proper names