18.10.2016 Views

Drupal 7 Module Development

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Appendix A<br />

Result objects<br />

The return value from a db_query() call is result object. In order to access the data<br />

returned by the database server, we need to iterate over the result set.<br />

$list = array();<br />

foreach ($result as $record) {<br />

$list[] = t('@name: @filename', array(<br />

'@name' => $record->name,<br />

'@filename' => $record->filename,<br />

));<br />

}<br />

By default, each $record in the result set is a stdClass object. We can, however, get<br />

the record as an associative array by telling the db_query() call that we want arrays<br />

instead. Here's how it is done:<br />

$result = db_query("SELECT name, filename FROM {system} WHERE type =<br />

:type AND status = :status", array(':type' => 'module', ':status' =><br />

1), array('fetch' => PDO::FETCH_ASSOC));<br />

Here, we specify a third parameter to db_query(), which is another associative<br />

array of options. We specify only one option, the fetch mode, which we set to<br />

PDO::FETCH_ASSOC. This tells the database layer we want associative arrays<br />

instead of stdClass objects.<br />

We can also fetch a single record, or even just a single field:<br />

// Fetch a single record as an object.<br />

$record = $result->fetchObject();<br />

// Fetch a single record as an array.<br />

$record = $result->fetchAssoc();<br />

// Fetch just the first field of the next record.<br />

$field = $result->fetchField();<br />

// Fetch the entire result set at once into an array.<br />

$records = $result->fetchAll();<br />

See the online documentation for more details about various ways to retrieve data<br />

from a result set.<br />

[ 365 ]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!