Checking if mysql_query returned anything or not


$query = "SELECT * FROM `table`";
$results = mysql_query($query, $connection);

If 'table' has no rows. whats the easiest way to check for this.?

10/18/2008 2:26:41 AM

Accepted Answer

You could use mysql_num_rows($results) to check if 0 rows were returned, or use this faster alternative:

$query = "SELECT COUNT(*) AS total FROM table";
$results = mysql_query($query, $connection);
$values = mysql_fetch_assoc($results);
$num_rows = $values['total'];
10/18/2008 2:25:04 AM

Jeremy Ruten's answer above is good and executes quickly; on the other hand, it only gives you the number of rows and nothing else (if you want the result data, you have to query the database again). What I use:

// only ask for the columns that interest you (SELECT * can slow down the query)
$query = "SELECT some_column, some_other_column, yet_another_column FROM `table`";
$results = mysql_query($query, $connection);
$numResults = mysql_num_rows($results);
if ($numResults > 0) {
   // there are some results, retrieve them normally (e.g. with mysql_fetch_assoc())
} else {
   // no data from query, react accordingly

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow