2

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.

5 Answers 5

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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;

Comments

1

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

Comments

0

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.

Comments

0

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: - MySQL PHP count(*) returning something weird - https://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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.