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
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()) {...} }
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()) {...} }
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!