0

How do you check if it actually found results in a mysql query in php

for eg

$usersearch=mysql_query("Select * FROM users WHERE username=$Searchboxinput");
if($usersearch==successfull){
//What happens when successfull
}
else{
//what happens when unsuccessfull
}

so if it found a user matching $searchboxinput it will do something and vice vera

Imad_bush
  • 3
  • 1
  • 3
  • 1
    You do NOT want to write new code using the old, deprecated, "mysql_query()" API. You want to use the newer [mysqli](http://www.php.net/manual/en/book.mysqli.php) or PDO interfaces. In any case, you can check the result for num rows > 0. – paulsm4 May 13 '13 at 17:55

4 Answers4

3

Use mysql_num_rows()

if(mysql_num_rows($usersearch) > 0){
//What happens when successfull
}
else{
//what happens when unsuccessfull
}

FYI, you shouldn't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

You may also be open to SQL injections.

Zoe
  • 27,060
  • 21
  • 118
  • 148
John Conde
  • 217,595
  • 99
  • 455
  • 496
1

Try,

//mysql_query returns resource when successful 
if(mysql_num_rows($usersearch) > 0 ) {...}
else {...}

Manual

Note: Mysql_* extensions are deprecated. Try using PDO or Mysqli extensions instead.

Teena Thomas
  • 5,139
  • 1
  • 13
  • 17
0

check like this

$count = mysql_num_rows($usersearch);


if($count)>0) {
}
chandresh_cool
  • 11,753
  • 3
  • 30
  • 45
0

$usersearch will contain a pointer to a query result set if the query is able to execute (regardless of whether there was a match), or if the query actually fails for some reason, it would hold a value of false.

As such, you need to check against the result set to see if there are actually any records returned. Oftentimes this is simply done using mysql_num_rows(). here is an example:

$usersearch=mysql_query("Select * FROM users WHERE username=$Searchboxinput");
if(false === $usersearch){
    // there was a problem running the query
    echo mysql_error();
} else if (mysql_num_rows($usersearch) === 0) {
    // no results were found
} else {
    //  you have at least one record returned
}

I would also suggest you learn to use mysqli or PDO as the mysql_* functions are deprecated.

Mike Brant
  • 70,514
  • 10
  • 99
  • 103