Nov 16

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.

  • Nov. 18, 2008

    Neat!

    Entirely unintentional, but nifty! I didn't realize D6 would handle that properly. Queries will still require some modification once you get to D7 (for the :placeholders and builders for modifier queries at least), but yeah, the named array format is probably a good habit to get into.

    Cool beans!

  • Rao V
    March 18, 2009

    Awesome may make switch to drupal

    I have been using wordpress for a while for my community blogs. I think i may want to switch over to drupal now because it seems more flexible and easier to hack / integrate with exiting php code.

About

I am Mikkel Høgh. I have been a web developer for about 8 years. I have my own company, Reveal IT, a long with a couple of friends. We specialize in helping our customers build awesome web sites with open source tools like Drupal and Django.

Subscribe

Elsewhere

Categories

Recent Posts

Archive

BlogRoll

Popular Posts