Home > Backend Development > PHP Tutorial > How to Fix the 'Call to a member function fetch_assoc() on a non-object' Error in MySQLi?

How to Fix the 'Call to a member function fetch_assoc() on a non-object' Error in MySQLi?

Linda Hamilton
Release: 2024-12-07 20:22:16
Original
450 people have browsed it

How to Fix the

Troubleshooting "Call to a member function fetch_assoc() on a non-object" Error

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.

Issue Analysis

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.

Solution

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;
}
Copy after login

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!

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