简体   繁体   中英

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

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?

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

在$ stmt-> execute()之后调用函数$ stmt-> store_result()此链接可能有助于http://php.net/manual/en/mysqli-stmt.num-rows.php

I think it's missing

$stmt->store_result();

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM