简体   繁体   English

PHP PDO语句使用SELECT返回不正确的行数?

[英]PHP PDO statement returns incorrect row count with SELECT?

Why does this portion of code return true even when it shouldn't be? 为什么这部分代码即使不应该返回也是true

$stmt = $dbh->prepare("SELECT COUNT(`user_id`) FROM `users` WHERE `username`= :username LIMIT 1");
$stmt->bindParam(':username', $username);
$stmt->execute();
return ($stmt->rowCount() == 1) ? true : false;

If I enter a username in a field that has already been registered, it returns true which then outputs: 如果我在已注册的字段中输入用户名,则返回true,然后输出:

That username has already been taken!

But if I enter a username that hasn't been registered, it still returns true and outputs the line above. 但是,如果我输入尚未注册一个用户名,它仍然返回true,输出线之上。 I'm unsure why this is and how it can be fixed. 我不确定为什么会这样以及如何解决。

I know that the PHP manual states that rowCount() has some issues with SELECT queries, but I can't find a workaround for this that returns the number of rows affected by a SELECT query. 我知道PHP手册指出rowCount()SELECT查询中存在一些问题,但我找不到一种解决方法,它返回受SELECT查询影响的行数。

Because COUNT() will always return 1 row, although its value may be 0. 因为COUNT()将始终返回1行,尽管其值可能为0。

You can do a SELECT TRUE instead: 您可以改用SELECT TRUE:

SELECT TRUE FROM `users` WHERE `username`= :username LIMIT 1

Or you can check if the value is greater than 0: 或者您可以检查该值是否大于0:

return ($stmt->fetchColumn() > 0);

BTW - the "? true : false" part is redundant; BTW - “?true:false”部分是多余的; having the boolean condition by itself does just that. 具有布尔条件本身就是这样。

You are checking the number of result rows. 您正在检查结果行数。 As your query returns always exactly one result row, rowCount() returns 1. The one result row will contain the count, eg 0 or 1 in with your query. 当您的查询总是返回一个结果行时, rowCount()返回1.一个结果行将包含计数,例如查询中的0或1。

You need to check that count value in the result-row or change your query to not return any rows in case the user does not exists. 您需要检查结果行中的计数值,或者更改您的查询以便在用户不存在时不返回任何行。

Try simple without binding: 尝试简单而不绑定:

$res = $dbh->query('SELECT COUNT(`user_id`) AS total FROM `users` WHERE `username`= "'.$username.'" ')->fetch();

return ($res['total'] == 1) ? true : false;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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