php - $result->num_rows 始终返回 0

标签 php mysql sql mysqli mysql-num-rows

在阅读了大量的帖子、教程和其他内容之后 - 我想在这里发帖并希望有人可以帮助我。 我尝试了所有能得到的建议,但仍然不起作用。

这是我的代码:

$prep_stmt = "SELECT id, DATE_FORMAT(added,'%d.%M'), title FROM offers ORDER BY added DESC LIMIT ?, ?;";
$stmt = $mysqli->prepare($prep_stmt);
$stmt->bind_param ('ii',$lowlimit, $page);
$stmt->execute();
$stmt->bind_result($id, $added, $title);
while ($stmt->fetch()) {
... # some random output here
}
$count = $stmt->num_rows;
echo "c -> ". $count;exit;

我总是得到“c -> 0”...但是已经有输出...那么我做错了什么? :/

最佳答案

在访问 num_rows 属性之前,您需要调用 store_result() 方法。

摘自 PHP manual documentation 的评论:

If you do not use mysqli_stmt_store_result(), and immediately call this function after executing a prepared statement, this function will usually return 0 as it has no way to know how many rows are in the result set as the result set is not saved in memory yet.

mysqli_stmt_store_result() saves the result set in memory thus you can immedietly use this function after you both execute the statement AND save the result set.

您的代码应如下所示:

$stmt->execute();
$stmt->store_result();

$stmt->bind_result($id, $added, $title);

while ($stmt->fetch()) {
    # some random output here...
}

$count = $stmt->num_rows;

关于php - $result->num_rows 始终返回 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22737237/

相关文章:

php - 从 Internet 浏览器检查元素时,如何在服务器上找到 .php 代码和文件?

php - 从完整 URL 中提取第一个 URL 片段

php - 检索 php/mysql 内动态下拉列表的数据

mysql - SQl - 我如何创建单个表的多个副本

javascript - 如何在 .js 文件的 javascript 函数中获取 php session 数据

php - URL 解析到数据库

mysql - mysql中的二进制日志错误

mysql - INNER JOIN 一个表,到另一个表的许多行

mysql - SQL 查询不是工作查询

SQL Select 在 where 子句中进行计算