提问人:Steven Oxley 提问时间:9/17/2008 最后编辑:DharmanSteven Oxley 更新时间:3/6/2021 访问量:2317
mysqli_stmt::num_rows() 返回错误的值
mysqli_stmt::num_rows() returns the wrong value
问:
我正在使用 mysqli 类和准备好的语句在 PHP 中编写数据库处理程序类。我试图打印出结果。它没有立即工作,所以我决定做一些调试。我尝试使用类中的方法,但它一直返回 0。我决定编写一小部分测试代码以使其更简单,以便我可以看到出了什么问题。然后,我能够返回我想要的数据,但是即使该方法实际上正在选择和检索一些数据,它仍然返回0。代码如下:num_rows()
mysqli_statement
num_rows()
$mysqli = new mysqli('localhost', 'username', 'password', 'database');
if(mysqli_connect_errno())
{
die('connection failed');
}
$statement = $mysqli->stmt_init();
$query = "SELECT name FROM table WHERE id = '2000'";
if($statement->prepare($query))
{
$statement->execute();
$statement->bind_result($name);
$statement->fetch();
$statement->store_result();
echo $statement->num_rows();
echo $name;
}
else
{
echo 'prepare statement failed';
exit();
}
预期结果是:
1name
实际结果是:
0name
谁能告诉我这是为什么?
答:
-1赞
Cetra
9/17/2008
#1
看起来你没有宣布$name。
另外,尝试删除 bind_result() 和 fetch(),使其读取如下内容:
$statement->execute();
$statement->store_result();
printf("Number of rows: %d.\n", $statement->num_rows);
6赞
Nathan Strong
9/17/2008
#2
我想知道 num_rows() 是否相对于当前结果集进行报告。在获取数据之前尝试捕获 num_rows()。例如:
if($statement->prepare($query))
{
$statement->execute();
$statement->store_result();
echo $statement->num_rows();
$statement->bind_result($name);
$statement->fetch();
echo $name;
}
这有什么影响吗?
评论
1赞
Steven Oxley
9/17/2008
事实上,这就是问题所在。为了使 num_rows() 返回正确的值,必须在 fetch() 之前调用 store_result()。
0赞
Nathan Strong
9/17/2008
这就是我的想法;获取数据会增加内部行计数器,这样你就可以做一些类似 while( $statement->num_rows() ) { /* 做事情 */ }
0赞
Sablefoste
6/14/2015
我坚信@StevenOxley的评论就是这个问题的答案。
0赞
Scott
3/9/2009
#3
num_rows
不是一个方法,而是一个属性。
0赞
Dharman
3/6/2021
#4
为了能够使用,您需要将所有行提取到 PHP 中。有两种方法可以获取所有内容:使用 缓冲或使用 手动获取所有行。mysqli_stmt::num_rows(),
store_result()
fetch()
在您的情况下,您已通过调用一次开始手动提取。当另一个提取过程正在进行时,您无法调用。调用失败,并显示错误*。fetch()
store_result()
store_result()
$statement->fetch();
$statement->store_result(); // produces error. See $mysqli->error;
echo $statement->num_rows();
最简单的解决方案是交换调用这两个方法的顺序。
$statement->store_result();
$statement->fetch(); // This will initiate fetching from PHP buffer instead of MySQL buffer
echo $statement->num_rows(); // This will tell you the total number of rows fetched to PHP
* 由于PHP中的一个bug,这个错误在异常报错模式下不会触发异常。只有使用 mysqli_error()
函数或其相应的属性才能看到错误消息。
评论