Fatal error: Call to a member function fetch_assoc() on a non-object
This error message is one of the most common indicators that your SQL query did not return the expected result set, or worse, returned nothing at all. When you see Fatal error: Call to a member function fetch_assoc() on a non-object, it means the $result variable passed into your fetch_assoc() loop is null. In PHP, this usually happens when mysqli_query fails silently and returns false instead of a resource object.
In the code snippet provided, the developer constructs a complex query to calculate image popularity based on vote sums and upload date differences. The logic attempts to sort images by a custom scoring function involving subqueries. While the intent is clearâretrieve recent high-scoring imagesâthe implementation contains a critical flaw that leads directly to the crash.
The root cause lies in how mysqli_query handles errors. When you execute $this->database->query($query), the method returns a resource on success and false on failure. If there is an SQL syntax error, a missing table, or a permission issue, query returns false. However, if you do not explicitly check the return value before iterating, PHP will attempt to call fetch_assoc() on that false value. This triggers the fatal error because false does not have methods like fetch_assoc().
The specific query in the example is particularly risky due to its complexity. It uses a subquery in the ORDER BY clause to calculate popularity:
ORDER BY ((SELECT SUM( image_id=`images`.image_id ) FROM `image_votes` AS score) / (SELECT DATEDIFF( NOW( ) , date_uploaded ) AS diff)) DESC
This syntax is highly problematic. First, subqueries inside an ORDER BY clause that rely on aggregate functions without a GROUP BY will fail if the underlying logic doesn't match the row count. More critically, the inner subqueries run once for every row in the outer query if not correlated properly, but here they are completely uncorrelated. The first subquery (SELECT SUM(...)) tries to sum image_ids from image_votes. If the join condition between images and image_votes is missing or incorrect, that subquery might return a value for no specific row context, or worse, cause a syntax error if the correlation isn't implicit but intended.
However, the immediate crash happens before the SQL logic is even fully evaluated in terms of data correctness. The code assumes $this->database->query($query) always succeeds. In reality, this query likely fails due to syntax errors (unrelated tables in subqueries without proper joining) or because it returns zero rows if no images match the criteria yet.
If the query returns an empty result set (zero rows), mysqli_query still returns a valid resource object containing 0 rows. In that case, the while loop simply never executes, and no error occurs. The error only appears when the query itself fails entirely.
To fix this, you must always validate the result of mysqli_query. Here is a safer pattern:
$result = $this->database->query($query);
if (!$result) {
// Log the actual error for debugging
throw new Exception("Database query failed: " . mysqli_error($this->database->conn));
}
$page = array();
while ($row = $result->fetch_assoc()) {
try {
array_push($page, new Image($row['image_id'], $view_deleted_images));
} catch (ImageNotFoundException $e) {
throw $e;
}
}
By checking if (!$result), you intercept the failure immediately. You can then inspect mysqli_error() to understand if it was a syntax error in that complex subquery or a missing table.
Additionally, consider simplifying the query logic. The current approach calculates popularity using uncorrelated subqueries inside the ORDER BY clause, which is inefficient and prone to logical errors. A more robust approach would be to join the image_votes table explicitly, use SUM() with GROUP BY image_id, and then order by that aggregate column. This ensures the database engine can optimize the scan correctly rather than recalculating subqueries for every row.
Finally, ensure that your Database class properly handles exceptions from the underlying MySQLi driver. If you are wrapping everything in a custom Database class, make sure it doesn't swallow errors or return null on failure. The error handling strategy should fail fast so that the application stack trace reveals exactly where the SQL went wrong.
