1

I have a MySQL keyword search on my website and it works fine. The problem is when someone searches a keyword I haven't added, nothing shows up on the results page.

Instead of nothing showing up I would like to have a no results found message.

So I used the code below:

if (mysql_num_rows($Recordset1) > 0) {
    // no results
    echo 'No results found.';
} else {
    do {
    // output
    } while($res = mysql_fetch_assoc($Recordset1));
}

The problem is whenever I search a keyword knowing it is in my db, I get my results along with a no results found message. (The no results found message also appears on the top left of my webpage pushing my entire website down.)

And when I searched a keyword I knew was not in my db, I didn't get a message at all, it showed nothing like before.

I played around with the greater, less than, and equal signs and got similar problems. I was told my logic was backwards, but I'm not sure how it should look.

Any help would be greatly appreciated, thanks in advance.

Sibbo
  • 3,796
  • 2
  • 23
  • 41
Will
  • 33
  • 2
  • 8

4 Answers4

1

do {} while loops aren't suitable for database fetching, unless you do a row fetch BEFORE entering the loop. For the first iteration of your output section, there won't be any results fetched from the database, so you'd be outputting essentially nothing.

mysql_num_rows() would return a 0 if there are no results, so you're actually inverting th elogic, saying there are no rows when there really are. Even a single row of results would make > 0 return a true and output "no results".

Marc B
  • 356,200
  • 43
  • 426
  • 500
1
if (mysql_num_rows($Recordset1) == 0) {
// no results
echo 'No results found.';
} else {
while($res = mysql_fetch_assoc($Recordset1)) {
// output
}
}

try it...

1.) if no result then mysql_num_rows would be 0 2.) before getting output you should fetch it to a variable not after using it

KoolKabin
  • 17,157
  • 35
  • 107
  • 145
0
if (mysql_num_rows($Recordset1) == 0) {
 . . .
Bill Karwin
  • 538,548
  • 86
  • 673
  • 828
0

Change your if condition to

if (mysql_num_rows($Recordset1) == 0) {

When you use > 0 it means that "there are results" and not "no results found".

Virendra
  • 2,560
  • 3
  • 23
  • 37