Runtime Error
Call to a member function fetchAll() on null in /var/www/html/database.php on line 56
What This Error Means
This error occurs when a developer tries to call a method on a null or non-object variable, which in this case is a result set from a SQL query.
Why It Happens
This error usually happens when the database query execution fails, or when the query returns no results, and the developer tries to call a method on the result set without checking if it's null.
How to Fix It
- 1To fix this error, you should check if the result set is not null before trying to call a method on it. You can do this by using the null coalescing operator (??) or by checking if the result set is an instance of PDOStatement.
Example Code Solution
$pdo = new PDO('mysql:host=localhost;dbname=mydb', 'username', 'password');
$result = $pdo->query('SELECT * FROM users WHERE id = 1');
// Assuming the query returns no results, $result will be null
foreach ($result->fetchAll() as $user) {
// Code here
}$pdo = new PDO('mysql:host=localhost;dbname=mydb', 'username', 'password');
$result = $pdo->query('SELECT * FROM users WHERE id = 1');
if ($result !== null && $result instanceof PDOStatement) {
foreach ($result->fetchAll() as $user) {
// Code here
}
} else {
// Handle the case where the query returned no results or failed
}Fix for Call to a member function fetchAll() on null in /var/www/html/database.php on line 56
Browse Related Clusters
Related PHP Errors
PDOStatement::execute(): SQLSTATE[HY000] [2002] No such file or direct
Unexpected '}' at end of file in /var/www/html/script.php on line 1
Fatal error: Uncaught PDOException: SQLSTATE[HY093]: Invalid parameter
Warning: Cannot redeclare class Foo in /var/www/html/autoloader.php on
Related PHP Blog Articles
Have a different error? Get an instant explanation.
Explain Another Error