Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to convert result of Drupal db_query to PHP array?

Tags:

drupal

In Drupal, I can execute a SQL as follows:

$query_object = db_query("SELECT * FROM {nodes}");

If I know the query returns only a single result (so only 1 row and 1 column), I can directly fetch it with:

$result = db_result($query_object);

If I got multiple results, I need to loop through them with something like:

$rows[] = array();
while (($row = db_fetch_object($query_object) != FALSE) {
  $rows[] = $row;
}

I'm wondering if there is an easier way to do that? Is there a way that I can transfer all results into an array with a single statement? Or isn't that working, because db_result returns a cursor-like object, where you can only fetch a single row each time?

like image 450
Sebi Avatar asked Jun 09 '11 14:06

Sebi


2 Answers

Not in Drupal 6.

In Drupal 7, there are fetch methods that can help to avoid loops like that. From http://drupal.org/node/310072:

<?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);
?>
like image 54
Berdir Avatar answered Sep 18 '22 09:09

Berdir


In Drupal 7, you can also use:

db_query('QUERY')->fetchAll(PDO::FETCH_ASSOC);
like image 26
Jeff Maes Avatar answered Sep 22 '22 09:09

Jeff Maes