tags:

views:

244

answers:

5

Hi all,

Im trying to figure out how to handle this is no results are returned, how would I code that?

while($row = mysql_fetch_array($Result))

So like if there a results: print them out

else: show a link

+4  A: 

You can use mysql_num_rows() to tell you how many results are found. Using that with a simple if-statement, and you can determine what action to take.

if (mysql_num_rows($result) > 0) {
  // do while loop
} else {
  // show link
}
Jonathan Sampson
Just wondering - will the resulting value from that function always be falsy if it fails or no results? Could omit the greater than 0 if so (I always have, but have never thought too much in depth about possible return values) +1
alex
"Return Values: The number of rows in a result set on success or FALSE on failure." It seems that this may return `0` if indeed there are zero results, but `false` if the function fails.
Jonathan Sampson
Excellent. Worked perfectly, better than how I had found.
jrutter
Glad to hear that, @jrutter. Keep up the great work!
Jonathan Sampson
A: 

http://ca3.php.net/manual/en/function.mysql-num-rows.php

if(mysql_num_rows($result) > 0) {
   while($row = mysql_fetch_array($result)) { ... }
} else {
  // show link
}
Mark
Excellent - thank you!
jrutter
A: 

I might have figured it out:

if (!($row = mysql_fetch_array($descResult)))
     {
     echo "<tr><td>Add Link</td></tr>";
}
jrutter
+1  A: 

Others suggest using mysql_num_rows() but you should be aware that that function works only if you use a buffered query. If you query using mysql_unbuffered_query(), the number of rows in the result is not available.

I would use a simple flag variable:

$found_row = false;

while ($row = mysql_fetch_array($result)) {
  $found_row = true;
  . . .
}

if ($found_row == false) {
  // show link
}

It may seem redundant to set $found_row to true repeatedly, but assigning a literal value to a variable ought to be an insignificant expense in any language. Certainly it is small compared to fetching and processing an SQL query result.

Bill Karwin
Languages should have a construct to avoid this problem, since it's so common. Something like `while($cond){$action}else{$code}`.
Mark
@Mark: Python has a while/else construct.
Bill Karwin
A: 

This can be done without mysql_num_rows() or an additional (flag) variable

if ( false===($row=mysql_fetch_array($result, MYSQL_ASSOC)) ) {
  echo 'no rows in result set';
}
else {
  do {
    echo $row['X'];
  } while ( false===($row=mysql_fetch_array($result, MYSQL_ASSOC)) );
}

but it duplicates the actual fetch command (one in the if-statement and one in the while-clause).

VolkerK