Helpful Fetch Methods for Drupal 7 Queries

Last modified
Sunday, February 5, 2017 - 21:25

Some helpful samples that can be used to process data after a query on Drupal.


<?php
// Retrieve all records into an indexed array of stdClass objects.
$result->fetchAll();

// Retrieve all records into an associative array keyed by the field in the result specified.
$result->fetchAllAssoc($field);

// Retrieve a 2-column result set as an associative array of field 1 => field 2.
$result->fetchAllKeyed();
// You can also specify which two fields to use by specifying the column numbers for each field
$result->fetchAllKeyed(0,2); // would be field 0 => field 2
$result->fetchAllKeyed(1,0); // would be field 1 => field 0

// Retrieve a 1-column result set as one single array.
$result->fetchCol();
// Column number can be specified otherwise defaults to first column
$result->fetchCol($column_index);
?>

Topic

Add new comment

This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.