tags:

views:

54

answers:

4

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.';
}
+8  A: 

Use mysql_num_rows() for this.

if( mysql_num_rows($query) == 0 ) {
    // No results returned
svens
+5  A: 

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";
}

?>
The MYYN
A: 

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.

Don
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.
brainimus
A: 

You could use empty either:

$num_rows = mysql_num_rows($result);

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