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

PHP 7.2 - Warning: count(): Parameter must be an array or an object that implements Countable

我刚刚将 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 有关,我找不到 Pure PHP[=20= 的解决方案].

PDO fetch returns 失败时为假。所以你也需要检查这个案例:

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';
}