mysqli_statement :: num_rows()返回错误的值

时间:2020-03-05 18:58:01  来源:igfitidea点击:

我正在使用mysqli类和准备好的语句在PHP中编写数据库处理程序类。我正在尝试打印结果。它没有立即起作用,所以我决定进行一些调试。我尝试使用mysqli_statement类中的num_rows()方法,但该方法始终返回0。我决定编写一小部分测试代码以使其更简单,以便我能发现问题所在。这样我就可以返回我想要的数据,但是即使num_rows()方法实际上正在选择和检索某些数据,它仍然返回0。这是代码:

$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

谁能告诉我为什么呢?

解决方案

回答

我们似乎没有声明$ name。

另外,尝试删除bind_result()和fetch(),使其读取如下内容:

$statement->execute();

$statement->store_result();

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

回答

我想知道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; 
}

这有什么作用吗?

回答

num_rows不是方法,而是属性。