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..

If You Appreciate What I Do Here On Seven PHP :: 7PHP, You Could Consider:

  1. Following me on Twitter | @7php
  2. LIKE-ing my FaceBook page
  3. Subscribe to my Email List - see top-right subscription box
  4. Help diffuse this interview to the PHP ecosystem - Share & Spread the word as far as you can ==> That would be a FREE way to thank me
  5. Use my DigitalOcean referral link if you plan to use it as your VPS (it starts at only $5/month btw) or if you can refer it to your friends, highly appreciated.
  6. Support via Paypal donate - my Paypal ID is w@7php.com

{I'm thankful to your response(s)!}

Speak Your Mind

*