简体   繁体   中英

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

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
}

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'];

Alternatively you can simply check if the result of mysql_fetch_assoc is false.

$query = "SELECT * FROM `table`";
$results = mysql_query($query, $connection);
$Row = mysql_fetch_assoc($results);
if ($Row == false)
{
  $Msg = 'Table is empty';
}

One thing i noticed that was missed was the fact that the query might not succeed, so you do need to check if the $results variable is set. I'll use the answer given by yjerem as an example.

$query = "SELECT COUNT(*) AS total FROM table";
$results = mysql_query($query, $connection);
if ($results) { // or use isset($results)
$values = mysql_fetch_assoc($results);
$num_rows = $values['total'];
}

If you loop through the results, you can have a counter and check that.

$x = 1;
$query = mysql_query("SELECT * FROM table");
while($row = mysql_fetch_assoc($query))
{
  $x++;
}
if($x == 1)
{
  //No rows
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM