How To Fix – Fatal error: Call to a member function fetch_object() on a non-object


When coding, it is always advisable you check code to make sure the syntax are correct as majority of bugs arises from it. If you are using an Integrated development environment (IDE) such as NetBeans, Dreamweaver or Aptana Studio, you are notified when there is (syntax) error in your code.

While working on a CMS I was building for a client, I encountered this PHP / MySQL error;

Fatal error: Call to a member function fetch_object() on a non-object in C:\xampp\htdocs\user_edit.php on line 7

Below is the code that resulted to that error;

 <?php
$result = $mysqli->query("SELECT profile_picture FROM users WHERE id=('$user_id'");
	while ($rows = $result->fetch_object()) {
            printf('<img src="%s" />', $rows->profile_picture);
         }
  ?>

I inserted the code in NetBeans and Aptana Studio, no error was shown.

Taking a close look at the code, you will see there’s a syntax error in the SQL SELECT Query as the id wasn’t having a closing parenthesis.
It is the SQL syntax error that resulted to the Fatal error: Call to a member function fetch_object() on a non-object.

The correct SQL is:

$result = $mysqli->query("SELECT profile_picture FROM users WHERE id=('$user_id')");

It is best practice you check if the SQL query was successful before retrieving content from database.
For example:

<?php
$result = $mysqli->query("SELECT profile_picture FROM users WHERE id=('$user_id')");
	if ($result) {
            while ($rows = $result->fetch_object()) {
                printf('<img src="%s" />', $rows->profile_picture);
         }
        }
        else {
            echo "Error with SQL";
        }
  ?>
Summary

We have seen from the article that the cause of Fatal error: Call to a member function fetch_object() on a non-object is as a result of mysqli_query returning FALSE on failure.

If you are using the depreciated mysql_fetch_array to retrieve the database content and you had similar above SQL query error, below is the error message you will get.

Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\user_edit.php on line 7



Don’t Want To Miss Our Update, Subscribe Now
About collizo4sky

Agbonghama Collins is a webdeveloper and an internet geek. I love writing and sharing the little idea & information i know. Hope you enjoyed my Article.

You can get in touch with him via these modes: Follow him on Twitter, add him on Facebook or on Google+

Genesis Framework for WordPress