db_select vs dynamic queries (pdo)

/* dynamic query */
$query = db_select('node', 'n');
$query->join('field_data_field_datum', 'date', 'n.nid = date.entity_id');
$query->condition('n.type', 'calender_item', '=')
condition('n.uid', $uid, '=')
fields('n', array('nid', 'title', 'uid'))
fields('date', array('field_datum_value'))
range(0, 50)
orderBy('title', 'ASC');
$result = $query->execute();
/* db query */
$result = db_query('
    SELECT n.nid, n.title, n.uid, date.field_datum_value
    FROM {node} n
    INNER JOIN field_data_field_datum date ON n.nid = date.entity_id
    WHERE n.uid = :uid
    ORDER BY n.title ASC
    LIMIT 50
    OFFSET 0'
':uid' => $uid)
  foreach (
$result as $row) {
// do stuff

Count example:

$count = db_query("SELECT count(nid) FROM {table}")->fetchField();

for PDO:

  $query = db_select('node', 'n');
  $result = $query->execute()->rowCount();

For quick reference see:


This is the company blog of
Drupal specialist Merge.nl

We are located in Breda (Netherlands) and build websites using Drupal. More about us.

Content on this blog is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Netherlands License.

Creative Commons License

Recent Comments