Fetching into a class

Last modified: August 12, 2009 - 17:14

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. This is due to a bug in PHP http://bugs.php.net/bug.php?id=46139.

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.

To fetch each row into its

fago - November 10, 2009 - 00:54

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

 
 

Drupal is a registered trademark of Dries Buytaert.