tags:

views:

588

answers:

4

My code looks like this:

$result = mysql_query("SELECT * FROM `picdb` WHERE `picid` = '$picid' ") or trigger_error(mysql_error()); 
while($row = mysql_fetch_array($result)){ 
foreach($row AS $key => $value) { $row[$key] = stripslashes($value); }

Problem is that when there is no row to select, nothing happens, my $row array is empty.

How can i have this present a message of "no row found" when no rows match the select?

+1  A: 
if (mysql_num_rows($result) == 0) {
    echo "Result is empty!";
}

You should've read the description of mysql_query, it gives you the answer: http://php.net/mysql_query

deceze
Won't work. $result is a resource that might be valid even though it doesn't contain any rows.
Emil H
`$result` is a resource, not a primitive type. You can not use `empty()`.
Andrew Moore
My bad, already changed it.
deceze
+6  A: 

Use mysql_num_rows() to determine the amount of rows in your result.

$result = mysql_query("SELECT * FROM `picdb` WHERE `picid` = '$picid' ") or trigger_error(mysql_error()); 

if(mysql_num_rows($result) == 0) {
  echo "No row found!"
} else {
  while($row = mysql_fetch_array($result)) { 
    foreach($row AS $key => $value) {
      $row[$key] = stripslashes($value);
    }
  }
}
Andrew Moore
+12  A: 

try

if (mysql_num_rows($result) == 0) {
  // Show message
} else {
  // do your while stuff here
}
Zed
+1 nice and clean
Roee Adler
+1  A: 

mysql_num_rows() only works on buffered queries. If you have potentially a large/huge result set you might switch to unbuffered queries and num_rows is not an option anymore.
You can test the return value of the first call to mysql_fetch_array(). If it's FALSE there were no matching records.

<?php
$result = mysql_query("SELECT * FROM `picdb` WHERE `picid` = '$picid' ") or trigger_error(mysql_error()); 

$row = mysql_fetch_array($result, MYSQL_ASSOC);
if ( !$row ) {
  echo '0 rows';
}
else {
  do {
    echo htmlspecialchars($row['x']), "<br />\n";
  } while($row=mysql_fetch_array($result, MYSQL_ASSOC));
}

The downside of this do { } while() is that the $row=mysql_fetch... code has been duplicated. But it's only a small doublet.

VolkerK