mysqli_statement::num_rows() returns the wrong value

∥☆過路亽.° 提交于 2020-01-03 05:46:05

问题


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();
}

So yeah, expected result is:

1name

And actual result is:

0name

Can anyone tell me why this is?


回答1:


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; 
}

Does that have any effect?




回答2:


num_rows is not a method, it's a property.




回答3:


It doesn't look like you've declared $name.

Also, try removing bind_result() and fetch() so it reads something like this:

$statement->execute();

$statement->store_result();

printf("Number of rows: %d.\n", $statement->num_rows);


来源:https://stackoverflow.com/questions/80292/mysqli-statementnum-rows-returns-the-wrong-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!