PHP $stmt->num_rows不能通过准备好的语句工作


PHP $stmt->num_rows doesnt work by prepared statements

我想检查if ($numRows >= 1),然后它应该返回一些东西。

当我使用$con->mysql("{QUERY}")时,它工作。

但是当我使用$stmt = $con->prepare("{QUERY}")时,它不起作用。

有人知道吗?

<标题> 工作方法
<?php
if ($result = $con->query("SELECT username FROM users WHERE username = 'test'")) {
    $numRows = $result->num_rows;
    echo $numRows;
}
?>

结果:1

不工作方法

<?php
$name = 'test';
$stmt = $con->prepare("SELECT username FROM users WHERE username = ?");
$stmt->bind_param('s', $name);
$name = 'test';
$stmt->execute();
$numRows = $stmt->num_rows;
echo $numRows;
?>

结果:0

您需要在调用->num_rows()方法之前从SELECT查询传输结果集。

// your code    
$stmt->execute();
$stmt->store_result();  
$numRows = $stmt->num_rows;
echo $numRows;

参考:

  • http://php.net/manual/en/mysqli.store-result.php