Mikkel Høgh

Coding the web since 1999

16 Nov 2008

Preparing for Drupal 7 by changing the way to make parameters for db_query.

After attending DrupalCon in Szeged and following the new database stuff, I thought a bit about how to make the transition easier when Drupal 7 comes out.

I didn’t think that it was anything special, but Robert Douglass encouraged me to share it, so here you are:

I figured out that you can actually use the Drupal 7-style of arguments to db_query right now (more or less).

The thing is that db_query in Drupal 6 allows you to use either the classic way with an arbitrary number of extra arguments to the db_query function or arguments as an array which is the future style.

The deal is that Drupal 6 takes the arguments in order, where Drupal 7 will use array keys (so I’d have :title in my query instead of %s).

So you can use the same arguments in Drupal 6 and Drupal 7, because Drupal 6 doesn’t care about which keys you have in your arguments array.

So whithout further ado, an example query from my TSearch module (the implementation of PostgreSQL’s TSearch in Drupal):

db_query("UPDATE {tsearch_node} SET vid = %d,
          node_tsvector =
            setweight(to_tsvector('%s'), 'A') ||
            setweight(to_tsvector('%s'), 'B') ||
            setweight(to_tsvector('%s'), 'C') ||
            setweight(to_tsvector('%s'), 'D'),
          updated = %d
          WHERE nid = %d",
        array(':vid' => $node->vid,
              ':title' => $text['title'],
              ':extra' => $text['extra'],
              ':teaser' => $text['teaser'],
              ':body' => $text['body'],
              ':time' => $_SERVER['REQUEST_TIME'],
              ':nid' => $nid,

Isn’t that neat? I’ve become quite fond of this syntax, because I think it’s easier to see what’s going on, and it’ll be even better in Drupal 7, where I don’t have to care about the ordering any longer.