How can the error "Fatal error: Call to a member function fetch_assoc() on a non-object" be fixed in PHP when using MySqli?
The error "Fatal error: Call to a member function fetch_assoc() on a non-object" occurs when trying to call the fetch_assoc() method on a variable that is not a valid result set object. This error commonly happens when there is an issue with the query execution or connection to the database. To fix this error, you need to check if the query execution was successful before trying to fetch data from the result set.
// Assuming $conn is the mysqli connection object and $query is the SQL query
$result = $conn->query($query);
if ($result) {
while ($row = $result->fetch_assoc()) {
// Process each row here
}
} else {
echo "Error executing query: " . $conn->error;
}
Keywords
Related Questions
- What are the key factors to consider when calculating progress based on time intervals in PHP?
- What strategies can be employed to ensure that user actions, such as logging out, are accurately tracked and reflected in the system for data accuracy and user accountability?
- Why is it advisable to avoid using "SELECT *" in SQL queries and what are the potential drawbacks of doing so in PHP applications?