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

79,001

PDO fetch returns false on failure. So you need to check this case too:

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';
}
Share:
79,001
Marwan Khaled
Author by

Marwan Khaled

Updated on November 02, 2020

Comments

  • Marwan Khaled
    Marwan Khaled over 3 years

    I just upgraded my PHP installation from version 5.6 to 7.2. I used the count() function on my login page like so:

    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;
    

    After searching, I found questions and answers similar to this one, but they all were related to WordPress, and I couldn’t find a solution for Pure PHP.