Parasolx

Professional in Drupal web development, theme designing, consultation and training

[Snippet] Drupal 7 DB Query

10 May 2014 - 09:35 pm

Drupal 7 implemented database abstraction layer which built up on top with PDO. This make Drupal 7 in one step forward more faster for querying data from database compare to Drupal 6. Below are the snippets that can really useful for drowling custom data from database.

$uid = 1;
$result = db_query('SELECT n.nid, n.title, n.created
FROM {node} n WHERE n.uid = :uid', array(':uid' => $uid));

// Fetch next row as a stdClass object.
$record = $result->fetchObject(); 

// Fetch next row as an associative array.
$record = $result->fetchAssoc();

// Fetch data from specific column from next row
// Defaults to first column if not specified as argument
$data = $result->fetchColumn(1); // Grabs the title from the next row

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

// Retrieve all records as stdObjects into an associative array
// keyed by the field in the result specified.
// (in this example, the title of the node)
$result->fetchAllAssoc('title');

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

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

// Count the number of rows
$result->rowCount();
Kategori: 
Tags: 
database
query
db query