Using db_select with conditional statements in Drupal 7

Using db_select with conditional statements in Drupal 7

While the debate never ends about using db_select versus db_query…some say db_select is slower and db_query should be used for simple queries, but there are obvious advantages to db_select with its extenders and much more.

Whatever your decision, here is one case where db_select is super nice. Instead of building the query string in a variable an throwing that into db_query with the needed arguments, you can continue to build the dynamic query as you go. Very nice and easier to read/maintain (for most).

function mymodule_get_node_count($tid, $type = NULL) {
  $query = db_select('taxonomy_index', 't');
  $query->condition('tid', $tid, '=');
  $query->addExpression('COUNT(*)', 'count_nodes');
  if (!empty($type)) {
    $query->join('node', 'n', 't.nid = n.nid');
    $query->condition('type', $type, '=');
  }
}

Comments are closed.