Last updated November 23, 2012. Created by ksenzee on September 30, 2008.
Edited by drupalshrek, mr.baileys, rszrama, Crell. Log in to edit this page.
Queries can be fetched into objects based on custom classes. For example, if we have a class named ExampleClass the following query will return objects of the type exampleClass.
<?php
$result = db_query("SELECT id, title FROM {example_table}", array(), array(
'fetch' => 'ExampleClass',
));
?>If the class has a __construct() method the objects will be created, the properties will be added to the object, and then the __construct() method will be called. For example, if you have the following class and query.
<?php
class exampleClass {
function __construct() {
// Do something
}
}
$result = db_query("SELECT id, title FROM {example_table}", array(), array(
'fetch' => 'ExampleClass',
));
?>The object will be created, the id and title properties will be added to the object, and then __construct() will be executed. The order of these events is due to a bug in PHP for versions less than 5.2.
If there is a __construct() method on the object and that needs to be executed before the properties are added to the object the following example shows how to do this.
<?php
$result = db_query("SELECT id, title FROM {example_table}");
foreach ($result->fetchAll(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, 'ExampleClass') as $record) {
// Do something
}
?>The arguments passed into fetchAll can be used in fetch the same way. PDO::FETCH_CLASS tells fetchAll to take the returned result set and add the values as properties to the object of type ExampleClass (the second argument). PDO::FETCH_PROPS_LATE tells fetchAll to add the result set as properties to the object after __construct() is called.
Comments
To fetch each row into its
To fetch each row into its own special class use
<?php$result->fetchAll(PDO::FETCH_CLASS | PDO::FETCH_CLASSTYPE);
?>
as $result->setFetchMode() might not work in this case, see http://bugs.php.net/bug.php?id=46292
fetchObject() is special
For whatever reason, fetchObject() must be given the class name as well in order to get that type of object back. In that case, you don't need the 'fetch' option in db_query() or db_select(). This may be a bug in PDOStatement, as opposed to Database.