5

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

6 Answers 6

13

https://www.php.net/manual/en/function.mysql-num-rows.php

if(mysql_num_rows($result) > 0) {
   while($row = mysql_fetch_array($result)) { ... }
} else {
  // show link
}
Sign up to request clarification or add additional context in comments.

Comments

6

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
}

3 Comments

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
"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.
Excellent. Worked perfectly, better than how I had found.
2

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.

2 Comments

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

Use even shorter syntax without insignificant mysql_num_rows to save processor time:

if($result) {
   // return db results
} else {
   // no result
}

Comments

0

I might have figured it out:

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

Comments

0

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).

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.