Drupal Database API: Load a Single Row

DrupalDatabase

How to load a single row as an associative array using Drupal 7's database API.

Drupal Database API: Load a Single Row

Note: This is a restored article from the original A thousand nodes blog (circa 2014).

When working with Drupal 7's database API, you'll often need to retrieve a single row from the database. Here's how to do it efficiently:

// Load a single row
$query = db_select('table_name', 't')
  ->fields('t')
  ->condition('t.id', $id)
  ->range(0, 1);
  
$record = $query->execute()->fetchAssoc();

// Now $record contains the row as an associative array
// You can access it like $record['field_name']

If you only want specific fields:

$query = db_select('table_name', 't')
  ->fields('t', array('field1', 'field2', 'field3'))
  ->condition('t.id', $id)
  ->range(0, 1);
  
$record = $query->execute()->fetchAssoc();

Alternative Methods

There are a few other ways to fetch a single row:

Using fetchObject()

$record = $query->execute()->fetchObject();
// Access as $record->field_name

Using db_query() Directly

$record = db_query('SELECT * FROM {table_name} WHERE id = :id', 
  array(':id' => $id))->fetchAssoc();

For Simple Primary Key Lookups

// A simplified method if you're looking up by primary key
$record = db_select('table_name', 't')
  ->fields('t')
  ->condition('id', $id)
  ->execute()
  ->fetchAssoc();

Remember to always properly sanitize your inputs when building database queries to avoid SQL injection attacks. Drupal's database API handles this automatically when you use the condition() method or parameter binding with db_query().

Continue Reading

Browse All Articles