Mysqli计数返回错误的数字

时间:2013-11-04 06:27:58

标签: php mysqli

所以我有这个

$countsql = <<<SQL
SELECT COUNT(*)
FROM `deathnote`
SQL;

if ($stmt = mysqli_prepare($db, $countsql)) {
/* execute query */
mysqli_stmt_execute($stmt);
/* store result */
mysqli_stmt_store_result($stmt);
printf("Number of rows: %d.\n", mysqli_stmt_num_rows($stmt));
}

这个输出是1。 现在,当我在我的服务器上进入PHP管理员并运行完全相同的查询时,我收到12的预期结果。

任何人都可以看到我哪里出错,或建议做什么? 谢谢你们!

4 个答案:

答案 0 :(得分:1)

$res = mysqli_query($db, "SELECT COUNT(*) FROM deathnote");
$row = mysqli_fetch_row($res)
echo "Number of rows: $row[0]\n";

答案 1 :(得分:0)

使用mysqli_stmt_num_rows或使用COUNT(*)不要混用两者。

使用mysqli_stmt_num_rows查询

SELECT *
FROM `deathnote`;


使用COUNT(*) 推荐使用这种方式来提高性能并快速执行代码

$res = mysqli_query("SELECT COUNT(*) FROM deathnote");
$row = mysqli_fetch_array($res)
echo $row[0];

答案 2 :(得分:0)

您想要COUNT(*)的值,而不是行数 - 行数始终为1:单行,包含一列,包含值COUNT(*)。

答案 3 :(得分:0)

你正在使用sql count函数非常错误这里基本上它是一个聚合函数,它只返回1,因为你使用了printf(“行数:%d。\ n”,mysqli_stmt_num_rows($ stmt));如果你想要你想要的结果是12,那么你可以使用mysqli_result,mysqli_fetch_array i-e