Restored guide

Querying Drupal Database and Fetching All Results Associative Array

Archived 2008–2011 · 2 min read · Eric London's Drupal Blog

The original entry lived on this blog between 2008 and 2011. The explanation here is rewritten from public Drupal APIs so the same path can be read again. The note is titled “Querying Drupal Database and Fetching All Results Associative Array” and is written for Drupal 6.x unless a line below says otherwise.

What you are solving

Use the database layer with placeholders. Drupal 6 uses db_query() with %d, %s, and %f. Avoid string concatenation, and page large result sets instead of loading every row into memory. The moving parts in the historical title are: querying, drupal, database, and, fetching, all, results, associative, array.

APIs and modules in play

  • a custom module with the narrowest hook that can see the data
  • clearing cache and the theme registry after the change

A practical approach

  1. Step 1. Name the outcome in one sentence: Querying Drupal Database and Fetching All Results Associative Array.
  2. Step 2. Reproduce it on a development copy with the same modules enabled.
  3. Step 3. Keep the change in a custom module or in the theme, and leave contributed code untouched.
  4. Step 4. Write the query with placeholders and LIMIT it while you inspect the shape of the rows.
  5. Step 5. Add an index only after you have seen the slow query in the log.

Example

The sample is illustrative. Rename the function, swap in your machine names, and run it on a development copy.

// Querying Drupal Database and Fetching All Results Associative Array
function notes_querying_drupal_database_and_fetching_all_result_recent($uid, $limit = 20) {
  $sql = "SELECT nid, title FROM {node} WHERE uid = %d AND status = 1 ORDER BY changed DESC";
  $result = db_query_range($sql, $uid, 0, (int) $limit);
  $rows = array();
  while ($row = db_fetch_object($result)) {
    $rows[] = $row;
  }
  return $rows;
}

Check before you deploy

  • Confirm the change on a database copy, then again with the theme registry and page cache cleared.
  • Watch the PHP error log and the watchdog table for the first real request.
  • If the change alters markup, recheck the path with a keyboard and without JavaScript.

Restored guide. The original post was published by Eric London on this domain. This text is a new explanation of that subject, not a reproduction of the archived wording.