首页 > 解决方案 > 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 参数。

标签: phppostgresqlpdo

解决方案


fetchAll()总是返回一个数组,你需要检查它是否不是空的。此外,您在检查后设置为$authed,事实证明,最后一个条件块(在 if 的情况下)将永远不会被执行。相反,您可以通过简单的. 这是它的外观示例。1$verify_auth$authed != 1else

$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().


推荐阅读