检查mysql_query是否返回任何内容

2022-08-30 20:30:18
$query = "SELECT * FROM `table`";
$results = mysql_query($query, $connection);

如果“表”没有行。检查此项的最简单方法是什么?


答案 1

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
}

答案 2

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

推荐