简体   繁体   中英

MYSQL db returns wrong count

This piece of code returns 1 every time even if there is no given email address in db table. As you I place die($count) right after bind_result. It returns 1 every time. Have you noticed any wrong in my code?

    $stmt = $db->prepare("SELECT COUNT(id) FROM `users` WHERE `email`=? LIMIT 1") or die($db->error);
    $stmt->bind_param("s", $email) or die ($stmt->error);
    $stmt->execute() or die ($stmt->error);
    $count=$stmt->bind_result($count) or die ($stmt->error);
            die($count);
            $stmt->close();
    return ($count > 0 ? true : false);

You didn't call $stmt->fetch() to put the result of the query into the bound variable $count.

The value of $count is therefore set to the return value of $stmt->bind_result() which is always true (1) or false (0).

See examples at http://php.net/manual/en/mysqli-stmt.bind-result.php , you use bind_result() to tell the statement what PHP variables to store results in, but you must fetch the results of the query as a separate call to fetch() .


Re comment: None of these functions return the result of your count.

The functions return TRUE on success, and FALSE on failure. They do not return the result of the query. That's why you bind a variable, so the fetch can store the result in that variable as a side effect -- not as a return value. You should not assign $count=*anything* .

Here's how your code should look:

$stmt = $db->prepare("SELECT COUNT(id) FROM `users` WHERE `email`=? LIMIT 1") 
    or die($db->error);
$stmt->bind_param("s", $email) 
    or die ($stmt->error);
$stmt->execute() 
    or die ($stmt->error);
$stmt->bind_result($count)  // do not use return value
    or die ($stmt->error);
$stmt->fetch() // do not use return value
    or die ($stmt->error);
print ($count);
$stmt->close()
    or die ($stmt->error);
return ($count > 0 ? true : false);

bind_result binds variables to a prepared statement for result storage, and returns TRUE on success or FALSE on failure.

$stmt->bind_result($count);
$stmt->fetch();
$stmt->close();
return ($count > 0 ? true : false); // return $count > 0; would be ok.

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