MYSQL 数据库返回错误的计数
即使数据库表中没有给定的电子邮件地址,这段代码每次都会返回 1。正如你一样,我将 die($count) 放在 bind_result 之后。每次都返回1。你注意到我的代码有什么错误吗?
$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);
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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您没有调用
$stmt->fetch()
将查询结果放入绑定变量 $count 中。因此,$count 的值设置为 $stmt->bind_result() 的返回值,该值始终为 true (1) 或 false (0)。
请参阅 http://php.net/manual/en/mysqli- 的示例stmt.bind-result.php,您使用
bind_result()
告诉语句将结果存储在哪些 PHP 变量中,但您必须以单独的调用方式获取查询结果fetch()
。回复评论:这些函数都不会返回计数结果。
这些函数在成功时返回 TRUE,在失败时返回 FALSE。它们不返回查询结果。这就是绑定变量的原因,因此获取可以将结果存储在该变量中作为副作用 - 而不是作为返回值。您不应分配
$count=*anything*
。您的代码应如下所示:
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 tofetch()
.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:
bind_result
将变量绑定到准备好的语句以存储结果,成功时返回 TRUE,失败时返回 FALSE。bind_result
binds variables to a prepared statement for result storage, and returns TRUE on success or FALSE on failure.