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

1
  • 1
    You do NOT want to write new code using the old, deprecated, "mysql_query()" API. You want to use the newer mysqli or PDO interfaces. In any case, you can check the result for num rows > 0. Commented May 13, 2013 at 17:55

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

0

check like this

$count = mysql_num_rows($usersearch);


if($count)>0) {
}

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.