I've been confused about why this wont work! My query executes perfectly fine in all aspects, but when I added the if check on the $row value, the echo message goes as expected (if there are no results), but the else will not kick when there is a match in my query??? Why is this not working? Someone please ease my pain and set me straight!!

$row = mysql_fetch_array($result);
if (!$row) {
    echo "Sorry brah. Nothing matches your search criteria.";
} else {

$i = 1;
while($row = mysql_fetch_array($result)) {
    echo "$i - " . $row['first_name'] . " " .  $row['last_name'] . " - " .   $row['address'] . "<br />";
$i++;
    } 
}
share|improve this question

2 Answers

up vote 8 down vote accepted
$row = mysql_fetch_array($result);  // this fetches the first row your result
...

in while loop you are again fecthing thr row from result. Which will not work if you have only one row in resul

use

if (mysql_num_rows($result) == 0) {
    echo "Sorry brah. Nothing matches your search criteria.";
} else {
    $i = 1;
    while($row = mysql_fetch_array($result)) {
        echo "$i - " . $row['first_name'] . " " .  $row['last_name'] . " - " .   $row['address'] . "<br />";
        $i++;
    } 
}
share|improve this answer
I took the liberty of editing your answer. mysql_num_rows($result) > 0, should be mysql_num_rows($result) == 0. Hope you don't mind. – fireeyedboy Mar 27 '11 at 7:54
@fireeyedboy : thanks. – Gaurav Mar 27 '11 at 7:58
Thanks for the clarification. SOLVED! – OldWest Mar 28 '11 at 21:30

try mysql_num_rows($result)==0 instead in the if statement

share|improve this answer

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.