I have a search form that checks a database and I want it to display a message if there are no records returned.... here's what I have so far which outputs a blank page when there are no records found: while($arr = mysql_fetch_assoc($result)){ extract($arr); if (!$arr) { echo "Sorry, there were no records in the database"; exit; } echo "Here are your records" . $arr; PHP: I think I have the wrong syntax on line three: if (!$arr) { PHP: Not sure though....
The if() is pointless since $arr will always be a valid array at that point in the while() loop. Instead, before the while() loop starts, do something like this: $sql = "select blahblah"; $result = mysql_query($sql); if (!mysql_num_rows($result)) { echo "Sorry, there were no records in the database"; exit; } while ($arr = mysql_fetch_assoc($result)) { do_amazing_things(); } PHP:
if (!mysql_num_rows($result)) { echo "Sorry, there were no records in the database"; exit; } PHP: Should be if (@mysql_num_rows($result)==0) { echo "Sorry, there were no records in the database"; }else{ //do something } PHP:
@ is evil. It's the cause of so many bugs. It should be removed from the language. If you want to be thorough and test separately for mysql_num_rows() returning false, that's great. But what you've provided gives the same results as what I provided, except that it masks errors. Any error in this context almost certainly points to something that should be dealt with, so masking them is a bad idea.
So much to absorb, I will look into these examples further. I feel like I am closer to my next php breakthough thanks to the help from DP members. Another thing, what is the purpose of the @?
If you put @ before a function call, then any non-fatal error from that function will not be displayed.
Its best to mask the mysql_num_rows as if it returns a 0 it will state a error, therfore you do not want that to occur you want to display your own error like, No results found.
Huh? If there are no result rows, no error message will ever be displayed; it will just politely return 0. That is not an error condition and is not treated as such. Have you actually tried it? mysql_num_rows() only throws an error when there are real problems, like an invalid statement handle.