简体   繁体   English

检查mysql_query是否返回任何东西

[英]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; 杰里米·鲁滕(Jeremy Ruten)的上述回答很好,并且执行迅速; 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: 您可以使用mysql_num_rows($ results)来检查是否返回了0行,或者使用以下更快的替代方法:

$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. 另外,您可以简单地检查mysql_fetch_assoc的结果是否为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. 我注意到错过的一件事是查询可能不会成功,因此您需要检查$ results变量是否已设置。 I'll use the answer given by yjerem as an example. 我将以yjerem给出的答案为例。

$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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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