Fatal error: Call to a member function fetch_assoc

2018-12-31 07:54发布

I'm trying to execute a few queries to get a page of information about some images. I've written a function

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"; //move to database class
    $result = $this->database->query($query);
    $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;
}

that selects a page of these images based on their popularity. I've written a Database class that handles interactions with the database and an Image class that holds information about an image. When I attempt to run this I get an error.

Fatal error: Call to a member function fetch_assoc() on a non-object

$result is a mysqli resultset, so I'm baffled as to why this isn't working.

标签: php mysql
4条回答
荒废的爱情
2楼-- · 2018-12-31 08:20

Most likely your query failed, and the query call returned a boolean FALSE (or an error object of some sort), which you then try to use as if was a resultset object, causing the error. Try something like var_dump($result) to see what you really got.

Check for errors after EVERY database query call. Even if the query itself is syntactically valid, there's far too many reasons for it to fail anyways - checking for errors every time will save you a lot of grief at some point.

查看更多
弹指情弦暗扣
3楼-- · 2018-12-31 08:20

Please check if you have already close the database connection or not. In my case i was getting the error because the connection was close in upper line.

查看更多
余生请多指教
4楼-- · 2018-12-31 08:29

That's because there was an error in your query. MySQli->query() will return false on error. Change it to something like::

$result = $this->database->query($query);
if (!$result) {
    throw new Exception("Database Error [{$this->database->errno}] {$this->database->error}");
}

That should throw an exception if there's an error...

查看更多
栀子花@的思念
5楼-- · 2018-12-31 08:37

I happen to miss spaces in my query and this error comes.

Ex: $sql= "SELECT * FROM";
$sql .= "table1";

Though the example might look simple, when coding complex queries, the probability for this error is high. I was missing space before word "table1".

查看更多
登录 后发表回答