mysql_query returns: how tell if no records returned?

How do you check if a mysql_query returns no records?

In the [greatly simplified] code below, the mysql_query is part of a “while” loop (not shown) and is executed multiple times. I only want the “<execute this>” part to be executed IF the mysql_query returns records.

What am I doing wrong?


$result = mysql_query ("SELECT Name FROM Info");

 if ($result != null)   // is this the proper syntax?

 {
  <execute this>
 }

use the mysql_num_rows() function

if(mysql_num_rows($result)!=0)
{
<execute this>
}

i would use:


$result = mysql_query ("SELECT Name FROM Info");

 if ($result){
  do this
 }
 else{
   nothing returned by the query
 }

beachball

beachball the problem with your code is that $result will still contain 1 even if no rows are returned. $result will be either 1 or 0 depending on whether the query executed successfully not whether ti returned any rows. For this you must use mysql_num_rows() as stated earlier.

Thanks–the mysql_num_rows() function worked!

oops…

/mental note: read the post more carefully :smiley:

however, if 0 rows are returned, whenever i use mysql_num_rows i get an error :frowning: and so use:

$result = mysql_query (“SELECT Name FROM Info”);

if ($result){
mysql_num_rows($result);
}
else{
nothing returned by the query
}

which avoids the error, cos if nowt returned then $result is false…

beachball

That is not true, your query must have been failing. If the query is successful and there are no rows returned mysql_num_rows() will return 0 which is what you want. If your query fails then mysql_num_rows() will produce an error. Like I said earlier, mysql_num_rows() only works on queries that were executed successfully. and the query result identifier in your case $result will be 1 if the query is successful no matter how many rows are returned.

the query were fine, but num_rows() were causin’ a big error…

maybe ur rite, maybe i’m wrng lol :smiley:

beachball

Was the error something along the lines of


Warning: Supplied argument is not a valid MySQL result resource in c:\\wwwroot\	est.php on line 14

If so that means the query was failing.

On a side note (I’m picky about this stuff), I just check for a straight-up value. What I mean is, instead of this…


if (mysql_num_rows($result) == 0) {

I use…


if (mysql_num_rows($result)) {

…it’s not a big deal, but it’s a nice shortcut I like, and I think it makes for more legible code, even though things are not “spelled out” quite as much. Your call on which to use.

Try @mysql_num_rows instead.