PHP Mysqli始终返回0行

时间:2018-08-10 10:32:10

标签: php mysqli

问题详细信息

我总是得到rows count = 0

enter image description here

下面是从数据库中获取信息的代码。

$con = mysqli_connect("localhost", "root", "", "homework");

$UserName = "test";
if($result = $con->prepare("SELECT * from tbluser where User_Name=?")) {
    $result->bind_param("s", $UserName);
    $result->execute();
    $row_cnt = $result->num_rows;
    echo $row_cnt; //Always returns 0 row
    $result->close();
}
$con->close();

下面是执行此行后的$result打印。 $result->execute();

echo "<pre>";
print_r($result);
echo "</pre>";

mysqli_stmt Object
(
    [affected_rows] => -1
    [insert_id] => 0
    [num_rows] => 0
    [param_count] => 1
    [field_count] => 4
    [errno] => 0
    [error] => 
    [error_list] => Array
        (
        )

    [sqlstate] => 00000
    [id] => 1
)

1 个答案:

答案 0 :(得分:1)

如手册中所述

  

如果不使用mysqli_stmt_store_result(),并且在执行准备好的语句后立即调用此函数,则该函数通常将返回0,因为它无法知道结果集中有多少行,因为结果集不是保存在内存中了。

// First add this so you are sure you will get shown any errors

ini_set('display_errors', 1); 
ini_set('log_errors',1); 
error_reporting(E_ALL); 
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

$con = mysqli_connect("localhost", "root", "", "homework");

$UserName = "test";
if($result = $con->prepare("SELECT * from tbluser where User_Name=?")) {
    $result->bind_param("s", $UserName);
    $status = $result->execute();

    // new line of code
    $result->store_result();

    $row_cnt = $result->num_rows;
    echo $row_cnt; //Always returns 0 row
    $result->close();
}
$con->close();