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 ?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With