PHP: PDO bindValue() 导致返回 0 个结果
我在使用 PDO bindValue() 函数时遇到了一些问题。每当我使用它时,我的查询总是返回 0 个结果。但是,如果我将 $user 和 $pass 直接放入 sql 中而不使用 bindValue() ,它就可以正常工作
$user 是一个字符串
$password 是 sha1() 哈希值
public function login($user, $pass) {
global $CMS;
$sql = "SELECT `username,`password` FROM `" . TB_PREFIX . "users` WHERE `username` = ':user' AND `password` = ':pass'";
$query = $CMS->prepare_query($sql);
$query->bindValue(':user', $user, PDO::PARAM_STR);
$query->bindValue(':pass', $pass, PDO::PARAM_STR);
$query->execute();
# User successfully authenticated
if ($query->rowCount() == 1) {
# Get all data from DB and populate class variables
self::populate_user_data($user);
session_register($user . "-" . base64_encode($_SERVER['REMOTE_ADDR']));
return true;
}
# User failed authentication
return false;
}
I've having some troubles with the PDO bindValue() function. Whenever I seem to use it, my queries always return 0 results. However it works fine if I put $user and $pass straight into the sql without the use of bindValue()
$user is a string
$password is a sha1() hash
public function login($user, $pass) {
global $CMS;
$sql = "SELECT `username,`password` FROM `" . TB_PREFIX . "users` WHERE `username` = ':user' AND `password` = ':pass'";
$query = $CMS->prepare_query($sql);
$query->bindValue(':user', $user, PDO::PARAM_STR);
$query->bindValue(':pass', $pass, PDO::PARAM_STR);
$query->execute();
# User successfully authenticated
if ($query->rowCount() == 1) {
# Get all data from DB and populate class variables
self::populate_user_data($user);
session_register($user . "-" . base64_encode($_SERVER['REMOTE_ADDR']));
return true;
}
# User failed authentication
return false;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不应该自己在值周围加上引号,它们将被添加(如果需要,例如在字符串的情况下 - 这种情况):
You should not put the quotes around the values yourself, they will be added (if needed, such as in the case of strings - this case):
准备好的语句中的占位符不得被引用; PDO 已经完成了所有的引用工作。你想要:
The placeholders in a prepared statement must not be quoted; PDO is already doing all the quoting. You want:
使用准备好的语句时,值会自动转义。
这意味着您不必在参数周围设置引号。
尝试一下:
你应该没问题。
不过,顺便说一句:您不应该按字面意思存储用户密码。查看这篇优秀文章:您可能正在存储密码错误
When using prepared statements, the values get escaped automagically.
This means, that you don't have to set quotes around the arguments.
try:
and you should be fine.
As a side note though: you should NEVER store user passwords literally. Check this excellent article: You're Probably Storing Passwords Incorrectly