PHP + PDO + FETCH_OBJ Issue + Notice: Trying to get property of non-object

ASSUMPTIONS:

  1. I’m expecting only 1 row of data for the fetch-ing
  2. I need the fetched-data to be in the form of an stdClass object
  3. You are familiar with using PDO – PHP Data Objects

This PDO error typically occurs when you try to fetch data into an stdClass object by using fetchAll()
By definition fetchAll returns an ARRAY containing all of the result set rows. Example of such an array is as follows:

Array
(
[0] => stdClass Object
(
[id] => 1
[name] => wasseem
[blog] => http://7php.com
)

)

CODE
$stdObj = $statement_handler->fetchAll(\PDO::FETCH_OBJ);

Now you see where the issue is? The object of type stdClass is there, BUT it is inside an array. To access the stdClass properties, you’ll need to loop inside the array.

What if you know that you are expecting only ONE row?

You do it in either way:
1) Access the object at the first index, e.g: $stdObj[0]->name
But I do not like this type; we fetched the data as an object to use it AS an object not as an object-array.

2) Another approach is to simply use the alternative fetchObject()
By definition, fetchObject fetches the NEXT row and returns it as an object (by default as stdClass object)

As you read it, it means it will fetch row by row. But if we already know we will have one row, we can just use it as a fetchAll, but this time returning an object.

CODE
$stdObj = $statement_handler->fetchObject();

Note here that you do not even have to set the \PDO::FETCH_OBJ this time.

How about your way of doing it? Did you find a better way? Use the comment form below to share your part..




Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.