1

I need a way to do this, If a mysql query dosn't retrieve any data, something happens. Here's an example.

$color="red";
$query = mysql_query("SELECT * FROM people WHERE shirt='$color'");
if($query = null){
echo 'No people wearing '.$color' shirts available.';
}
0

4 Answers 4

9

Use mysql_num_rows() for this.

if( mysql_num_rows($query) == 0 ) {
    // No results returned
Sign up to request clarification or add additional context in comments.

Comments

5

Use mysql_num_rows to check, how many rows have been returned by your query.

<?php

$link = mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("database", $link);

$result = mysql_query("SELECT * FROM table1", $link);
$num_rows = mysql_num_rows($result);

if( $num_rows == 0 ) {
    // No results returned
    echo "No results!";
} else {
    echo "$num_rows Rows\n";
}

?>

Comments

0

Besides the mysql_num_rows() there is also COUNT() which could be used like this:

"SELECT COUNT(*) FROM people WHERE shirt='$color'"

You might actually need more data from the database but if you only need a number then this would remove the need for an if.

1 Comment

A downside to this approach is that to actually get the data (if it exists) you have to make at least two calls to the database. It's also possible that the data may change between the calls.
0

You could use empty either:

$num_rows = mysql_num_rows($result);

if(empty($num_rows)){
    echo 'No results';
}

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.