无法从PDO数组中获取值


Unable to get value from a PDO array

我是PHP的新手,一直在学习Lynda.com教程(尽管他们仍然使用mysql而不是mysqli或PDO)。

我在使用从查询中获得的数据时遇到了问题。

我将以我的登录页面为例,省略连接到数据库的部分:

$login_username = trim(htmlspecialchars($_POST['username'])); 
$password = trim(htmlspecialchars($_POST['password'])); // from login form
$stmt = $db->prepare("SELECT * FROM users 
                     WHERE username = :login_username");
$stmt->bindParam(':login_username', $login_username);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() > 0 && $result = password_verify($password,$result['hashed_password'])) {
$_SESSION['logged_in_id'] = $result['id'];
$_SESSION['logged_in_username'] = $login_username; //this was the only way I could pass the username as I could not get it from $result['username']
$_SESSION['first_name'] = $result['first_name'];
$_SESSION['last_name'] = $result['last_name'];

没有任何内容传递到会话,也没有任何错误。我也不能回显$result的值。如果我只是尝试回显$result,那么我只得到值1

请帮忙!

您的问题是:

... && $result = password_verify($password,$result['hashed_password'])

请注意,$result是一个数组,它包含您刚刚获取的行,并且您在这里为它分配了一个新值;您正在覆盖$result变量,因此之后的所有赋值都将失败。

你可能想要这样的东西:

... && password_verify($password,$result['hashed_password'])

还要注意,您不应该依赖rowCount(),因为这不一定是您对SELECT语句的期望。

由于您已经在获取一行,您可以简单地执行以下操作:

 if ($result && password_verify($password,$result['hashed_password']))

如果没有结果,则永远不会检查第二个条件,因此不会导致警告或错误。