检查mysql_query是否返回任何内容

时间:2008-10-18 02:22:07

标签: php sql mysql

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

如果'table'没有行。什么是最容易检查的方法。?

5 个答案:

答案 0 :(得分:31)

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
}

答案 1 :(得分:14)

您可以使用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'];

答案 2 :(得分:8)

或者,您只需检查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';
}

答案 3 :(得分:0)

我注意到遗漏的一件事是查询可能不成功,所以你需要检查是否设置了$ 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'];
}

答案 4 :(得分:-6)

如果你遍历结果,你可以有一个计数器并检查它。

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