mysqli prepared statement num_rows returns 0 while query returns greater than 0

不想你离开。 提交于 2020-05-20 02:42:56

问题


I have a simple prepared statement for an email that actually exists:

$mysqli = new mysqli("localhost", "root", "", "test");
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$sql = 'SELECT `email` FROM `users` WHERE `email` = ?';
$email = 'example@hotmail.com';

if ($stmt = $mysqli->prepare($sql)) {
    $stmt->bind_param('s', $email);
    $stmt->execute();

    if ($stmt->num_rows) {
        echo 'hello';
    }

    echo 'No user';
}

Result: echos No user when it should echo hello

I ran the same query in the console and got a result using same email as above.

I tested using a simple mysqli query as well:

if ($result = $mysqli->query("SELECT email FROM users WHERE email = 'example@hotmail.com'")) {
    echo 'hello';

}

Result: what I expected hello

Also $result's num_rows is 1.

Why is the prepared statment's num_row not greater than 0?


回答1:


When you execute a statement through mysqli, the results are not actually in PHP until you fetch them -- the results are held by the DB engine. So the mysqli_stmt object has no way to know how many results there are immediately after execution.

Modify your code like so:

$stmt->execute();
$stmt->store_result(); // pull results into PHP memory

// now you can check $stmt->num_rows;

See the manual

This doesn't apply to your particular example, but if your result set is large, $stmt->store_result() will consume a lot of memory. In this case, if all you care about is figuring out whether at least one result was returned, don't store results; instead, just check whether the result metadata is not null:

$stmt->execute();
$hasResult = $stmt->result_metadata ? true : false;

See the manual




回答2:


call function $stmt->store_result() after $stmt->execute() this link might help http://php.net/manual/en/mysqli-stmt.num-rows.php




回答3:


I think it's missing

$stmt->store_result();

if ($stmt->num_rows) {
    echo 'hello';
}

http://php.net/manual/en/mysqli-stmt.num-rows.php



来源:https://stackoverflow.com/questions/45901577/mysqli-prepared-statement-num-rows-returns-0-while-query-returns-greater-than-0

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