开发者

How to check if results on while($row = mysql_fetch_array in PHP

开发者 https://www.devze.com 2022-12-14 07:32 出处:网络
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))

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开发者_如何学Python out

else: show a link


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
}


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
}


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.


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

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


I might have figured it out:

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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消