Home > Backend Development > PHP Tutorial > Why Am I Getting a 'Fatal Error: fetch_assoc() on a Non-Object' in My PHP Database Queries?

Why Am I Getting a 'Fatal Error: fetch_assoc() on a Non-Object' in My PHP Database Queries?

Linda Hamilton
Release: 2024-12-09 00:23:14
Original
695 people have browsed it

Why Am I Getting a

Fatal Error: fetch_assoc() on a Non-Object

When executing database queries, you may encounter the following error message:

Fatal error: Call to a member function fetch_assoc() on a non-object
Copy after login

This error occurs when the fetch_assoc() method is called on a non-object, typically a mysqli_result object.

Problem Analysis:

In the provided code snippet, you may have written a function like the following:

function get_recent_highs(...){
    $result = $this->database->query($query);
    while($row = $result->fetch_assoc()) {...}
}
Copy after login

If $result is a non-object, the fetch_assoc() call will fail. This can occur if there is an error in the SQL query, which causes query() to return false instead of a result object.

Solution:

To resolve the error, check the return value of query(). If it returns false, throw an exception or handle the error accordingly. For instance:

function get_recent_highs(...){
    $result = $this->database->query($query);
    if (!$result) {
        throw new Exception("Database Error");
    }
    while($row = $result->fetch_assoc()) {...}
}
Copy after login

By catching the error in query(), you can ensure that fetch_assoc() is only called on a valid result object, preventing the non-object error.

The above is the detailed content of Why Am I Getting a 'Fatal Error: fetch_assoc() on a Non-Object' in My PHP Database Queries?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template