views:

92

answers:

5

I noticed that a lot of tutorial instructions often have this code:

$sql="SELECT * from table";
$num=mysql_num_rows();

if ($num > 0)
{
do something
}

Why do they have to use that condition "if ($num > 0)" when I write this code that I think is compact and readable:

$sql="SELECT * from table";
$itExists=mysql_num_rows();

if ($itExists)
{
do something
}

does mysql_num_rows ever return a negative integer? Doesn't PHP always equate 0 to false? I've used this approach and noticed nothing different or unusual.

+1  A: 

Both ways work just fine. I don't know why you wouldn't choose the second method.

Delan Azabani
+1  A: 

Why would you assign the number of rows returned to a variable with a bool name like itExists? By doing this you are making information that could be used later less useful. It's better to assign the number of rows (mysql_num_rows()) to a variable that says it holds a number of rows (numRows or in this case num).

Having something like itExists assigned to 4, 5 or 6 isn't good practice. It's in this way that the first method is better.

$pages = $numRows / $itemsPerPage;
//works better than...
$pages = $itExists / $itemsPerPage;
Sam152
+3  A: 

Tutorials probably try to make the code as clear, intuitive and explicit as possible. Using mysql_num_rows, whose name clearly implies an integer, as a boolean, is somewhat counter-intuitive. The comparison with zero is implicit. By contrast, if it is perceived as a number, then checking that it’s greater than zero is intuitive and obvious and therefore less confusing.

Timwi
A: 

According to http://php.net/manual/en/function.mysql-num-rows.php, it returns FALSE on an error. I'm pretty sure FALSE > 0 is FALSE, so the two are equivalent.

OTOH, it's traditional in other languages (and possibly in older versions of PHP) to return negative numbers on an error. Some OpenSSL signature-verification functions return 1 for "valid", 0 for "invalid", and -1 for "error". It's a coding style thing.

tc.
A: 

PD. If you only need to check if there are rows, using mysql_num_rows is not very efficient, it is better to count within the SQL statement:

SELECT COUNT(*) FROM table

See: - http://stackoverflow.com/questions/1300093/mysql-php-count-returning-something-weird - http://stackoverflow.com/search?q=php+mysql+count+rows


Doesn't PHP always equate 0 to false?

Not always:

$a = 0;
if (!$a) echo 'pass <br />'; else echo 'fails <br />';
if ($a == false) echo 'pass <br />'; else echo 'fails <br />';
if ($a === false) echo 'pass <br />'; else echo 'fails <br />';

See: http://php.net/manual/en/language.operators.comparison.php

Luistar15