PHP 7.2 - 警告:count():参数必须是实现Countable [closed]的数组或对象

2022-08-31 00:51:13

我刚刚将PHP安装从版本5.6升级到7.2。我在登录页面上使用了该功能,如下所示:count()

if (!empty($_POST['username']) && !empty($_POST['password'])):
    $records = $conn->prepare('SELECT id,username,password FROM users WHERE username = :username');
    $records->bindParam(':username', $_POST['username']);
    $records->execute();
    $results = $records->fetch(PDO::FETCH_ASSOC);

    $message = '';
    
    if (count($results) > 0 && password_verify($_POST['password'], $results['password'])) {
        $_SESSION['user_id'] = $results['id'];
        header("Location: /");
    } else {
        $message = 'Sorry, those credentials do not match';
    }
endif;

搜索后,我发现了与此类似的问题和答案,但它们都与WordPress有关,我找不到纯PHP的解决方案


答案 1

PDO 在失败时返回 false。所以你也需要检查这种情况:fetch

if ($results && count($results) > 0 && password_verify($_POST['password'], $results['password'])) {
    $_SESSION['user_id'] = $results['id'];
    header("Location: /");
} else {
    $message = 'Sorry, those credentials do not match';
}

答案 2

推荐