Imad_bush
Imad_bush

Reputation: 3

Check if mysql query found results PHP

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

Upvotes: 0

Views: 93

Answers (4)

John Conde
John Conde

Reputation: 219844

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.

Upvotes: 3

Mike Brant
Mike Brant

Reputation: 71384

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

Upvotes: 0

Teena Thomas
Teena Thomas

Reputation: 5239

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.

Upvotes: 1

chandresh_cool
chandresh_cool

Reputation: 11830

check like this

$count = mysql_num_rows($usersearch);


if($count)>0) {
}

Upvotes: 0

Related Questions