Drupal SQL query examples

Code snippet examples for making SQL queries - generally within custom node.tpl.php page templates.

Fetching a single field

    $sql = 'SELECT n.field_my_field FROM {field_table_name} n WHERE n.entity_id = 6';
    $result = db_query($sql)->fetchField();
    print $result;

Using variables in your SQL queries

   $result = db_query_range('SELECT n.title, n.body, n.created FROM {node} n WHERE n.uid = %d', $uid, 0, 10);
   while ($node = db_fetch_object($result)) {

%d takes $uid and passes it through function _db_query_callback (as $args). This ensures that $uid value is sanitised and safe. If $uid were a string value, it would use the %s.

  • %d is used for numbers (integers)
  • %s is used for letters (strings;)
  • %b is used for true/false/null
Justin Chevallier

Justin Chevallier

Avid Drupal site builder & user for +10 years.

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.