Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 761
Marwan Khaled Avatar asked Jul 30 '18 13:07

Marwan Khaled


People also ask

How do you solve count (): parameter must be an array or an object that implements countable?

In this case, a simple fix is to change line 302 to: if (is_countable($tombstones) && count($tombstones) > 0) : is_countable() has been introduced in PHP 7.3 exactly for this purpose.

How do you define a count in PHP?

We can use the PHP count() or sizeof() function to get the particular number of elements or values in an array. The count() and sizeof() function returns 0 for a variable that we can initialize with an empty array. If we do not set the value for a variable, it returns 0.

How do you count occurrences of each element in an array in PHP?

The array_count_values() function returns an array with the number of occurrences for each value. It returns an associative array. The returned array has keys as the array's values, whereas values as the count of the passed values.

Is countable in PHP?

The is_countable() function checks whether the contents of a variable is a countable value or not. This function returns true (1) if the variable is countable, otherwise it returns false/nothing.


1 Answers

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';
}
like image 169
Olim Saidov Avatar answered Oct 14 '22 07:10

Olim Saidov