Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning Array of Objects from PDO

Tags:

php

mysql

pdo

I have a PHP class (POJO_FOO) which maps to a table (TABLE_FOO).

e.g. one row equal to one object of that class.

Now I am writing a manager which returns array of such objects matching a particular query. Using PDO, how can I return array of objects ?

When I do simple fetchAll, it returns array (representing number of results) of associative array (column => value). Is there a option in fetchALL which can give me result in form of array of objects ?

like image 512
mrd081 Avatar asked Aug 28 '12 08:08

mrd081


People also ask

What does PDO fetchAll return?

PDOStatement::fetchAll() returns an array containing all of the remaining rows in the result set. The array represents each row as either an array of column values or an object with properties corresponding to each column name. An empty array is returned if there are zero results to fetch.

What is PDO :: Fetch_obj?

Returns an array indexed by column number as returned in your result set, starting at column 0. PDO::FETCH_OBJ. Returns an anonymous object with property names that correspond to the column names returned in your result set.


1 Answers

you can use PDO::FETCH_CLASS to hydrate your class with your data :

return $pdo->query('SELECT * FROM tablefoo')->fetchAll(PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE,'POJO_FOO');

it is also useful to use PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE because it makes the construction of the object more consistent. Habitualy your constructor is called before everything. If you do not use FETCH_PROPS_LATE it will called after your properties are hydrated.

like image 177
artragis Avatar answered Oct 25 '22 15:10

artragis