mysqli_statement :: num_rows()返回错误的值 [英] mysqli_statement::num_rows() returns the wrong value
问题描述
我正在使用mysqli类和准备好的语句在PHP中编写数据库处理程序类.我正在尝试打印结果.它没有立即起作用,所以我决定进行一些调试.我尝试使用mysqli_statement
类中的num_rows()
方法,但是该方法始终返回0.我决定编写一小部分测试代码以使其更简单,以便我可以发现问题所在.这样便可以返回所需的数据,但是num_rows()
方法仍然返回0,即使它实际上是在选择和检索某些数据.这是代码:
I was writing a database handler class in PHP using the mysqli class and prepared statements. I was attempting to print out the result. It didn't work right off the bat so I decided to do some debugging. I tried to use the num_rows()
method from the mysqli_statement
class, but it kept returning 0. I decided to write a small portion of test code to keep it simpler so I could see what was going wrong. I was then able to return the data I wanted, but the num_rows()
method still returns 0 even when it is actually selecting and retrieving some data. Here is the code:
$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
有人可以告诉我为什么吗?
Can anyone tell me why this is?
推荐答案
我想知道num_rows()是否相对于当前结果集进行报告.尝试在获取数据之前捕获num_rows().例如
I wonder if num_rows() is reporting relative to the current resultset. Try capturing num_rows() prior to fetching the data. e.g.
if($statement->prepare($query))
{
$statement->execute();
$statement->store_result();
echo $statement->num_rows();
$statement->bind_result($name);
$statement->fetch();
echo $name;
}
有没有效果?
这篇关于mysqli_statement :: num_rows()返回错误的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!