php - PHP PDO 查询不返回任何数据,返回显示数据的 isset()
问题描述
我有一些基本的 php 代码,它试图对数据库中的用户名和密码进行身份验证。如果用户和通行证成功匹配,则应该打印“已验证”。但是,查询没有返回任何数据。此外,我用来检查是否返回任何数据的 isset() 表明该数组中有值。
这里出了什么问题,我怎样才能让这个 pdo 查询返回请求的数据?
这是有问题的代码。
$stmt = $pd->prepare("SELECT username from users where username = :logon and password = :passwd");
$stmt->bindParam(':logon', $_POST['username'], PDO::PARAM_STR);
$stmt->bindParam(':passwd', $_POST['password'], PDO::PARAM_STR);
$stmt->execute();
$verify_auth = $stmt->fetchAll();
if(isset($verify_auth)){
echo "Authenticated locally";
$authed = 1;
//do something here
}
elseif($authed != 1){
echo "<b>Failure to authenticate</b>";
}
即使凭据错误,每次运行“本地身份验证”时也是如此。
即使使用正确的凭据,该verify_auth
数组似乎也始终为空。
已成功分配 post 参数。
解决方案
fetchAll()
总是返回一个数组,你需要检查它是否不是空的。此外,您在检查后设置为$authed
,事实证明,最后一个条件块(在 if 的情况下)将永远不会被执行。相反,您可以通过简单的. 这是它的外观示例。1
$verify_auth
$authed != 1
else
$stmt = $pd->prepare("SELECT username from users where username = :logon and password = :passwd");
$stmt->bindParam(':logon', $_POST['username'], PDO::PARAM_STR);
$stmt->bindParam(':passwd', $_POST['password'], PDO::PARAM_STR);
$stmt->execute();
$verify_auth = $stmt->fetchAll();
if ($verify_auth) {
echo "Authenticated locally";
$authed = 1;
//do something here
} else {
echo "<b>Failure to authenticate</b>";
}
isset()
非常有用,但在这种特殊情况下不是。它检查变量集,所以即使它有一个空值,它也会被设置并isset()
给你true
. 但是如果有一个不存在的变量或数组索引,它会给出false
. 在您的特定情况下,您可以使用isset($verify_auth[0])
,它会true
在$stmt->fetchAll()
.
推荐阅读
- java - maven 项目特定脚本的最佳方法?
- python - 子类可以在 pydantic 中继承其基类根验证器吗?
- zsh - 如何配置 zsh 以完成部分单词,但不区分大小写?
- python - 为什么哈希表除了数据值之外还存储键值?
- java - 如何获取 UI 的权限名称?
- java - 无法访问类“java.lang.String”。检查您的模块类路径是否存在缺失或冲突的依赖项
- python - 验证从谷歌驱动器(python)下载excel文件
- python - 在 Discord.py 机器人中记录删除消息的人
- javascript - XMLHTTPrequest 不查询内部 hosts 文件
- c++ - (OpenGL) EBO 是否可以仅应用于指定的 VBO 而不是 VAO 中的所有 VBO?