When executing a database query using the mysqli extension, it's possible to encounter the error "Fatal error: Call to a member function fetch_assoc() on a non-object." This error occurs when the query fails and the resulting mysqli resultset is null.
In the given code snippet, the error arises because the $result variable is not being checked for errors after the query is executed. Hence, it is possible that $result is null if the query failed, causing the subsequent call to fetch_assoc() to fail.
To resolve this issue, it is necessary to check the result of the mysqli_query() call for errors. If the query fails, an exception should be thrown to indicate the error. The revised code below:
function get_recent_highs($view_deleted_images = false) { $lower = $this->database->conn->real_escape_string($this->page_size * ($this->page_number - 1)); $query = "SELECT image_id, date_uploaded FROM `images` ORDER BY ((SELECT SUM( image_id=`images`.image_id ) FROM `image_votes` AS score) / (SELECT DATEDIFF( NOW( ) , date_uploaded ) AS diff)) DESC LIMIT " . $this->page_size . " OFFSET $lower"; $result = $this->database->query($query); if (!$result) { throw new Exception("Database Error [{$this->database->errno}] {$this->database->error}"); } $page = array(); while($row = $result->fetch_assoc()) { try { array_push($page, new Image($row['image_id'], $view_deleted_images)); } catch(ImageNotFoundException $e) { throw $e; } } return $page; }
By adding the if (!$result) check, the code ensures that any database errors are handled gracefully and an appropriate exception is thrown.
The above is the detailed content of How to Fix the 'Call to a member function fetch_assoc() on a non-object' Error in MySQLi?. For more information, please follow other related articles on the PHP Chinese website!