php 检查 mysql_query 是否返回任何内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/214419/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Checking if mysql_query returned anything or not
提问by Piskvor left the building
$query = "SELECT * FROM `table`";
$results = mysql_query($query, $connection);
If 'table' has no rows. whats the easiest way to check for this.?
如果“表”没有行。检查这个的最简单方法是什么。?
采纳答案by Jeremy Ruten
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'];
回答by Piskvor left the building
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:
Jeremy Ruten 上面的回答很好并且执行得很快;另一方面,它只给你行数而没有别的(如果你想要结果数据,你必须再次查询数据库)。我使用的是什么:
// 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
}
回答by Toby Allen
Alternatively you can simply check if the result of mysql_fetch_assoc is false.
或者,您可以简单地检查 mysql_fetch_assoc 的结果是否为假。
$query = "SELECT * FROM `table`";
$results = mysql_query($query, $connection);
$Row = mysql_fetch_assoc($results);
if ($Row == false)
{
$Msg = 'Table is empty';
}
回答by Tebo
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.
我注意到遗漏的一件事是查询可能不会成功,因此您需要检查是否设置了 $results 变量。我将以 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'];
}
回答by user24632
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
}

