Stochastic Geometry

January 4, 2008

Multiple databases in Drupal

Filed under: PHP — Mark Dennehy @ 10:47

Have to say, while MDB2 has the more straightforward way of accessing multiple databases (just create more database objects using MDB2::factory()), drupal’s way of doing things is a long way from horrible.

To initialise:

$db_url['default'] = 'mysql://drupal:drupal@localhost/drupal';
$db_url['mydb'] = 'mysql://user:pwd@localhost/anotherdb';
$db_url['db3'] = 'mysql://user:pwd@localhost/yetanotherdb';

And then to use:

db_set_active('mydb');
db_query('SELECT * FROM table_in_anotherdb');
//Switch back to the default connection when finished.
db_set_active('default');

Quite straightfoward looking. Now to see if it actually works! 🙂

Advertisements

5 Comments »

  1. And of course it does, but there are some caveats – you should call db_set_active(‘default’) immediately on finishing your db_query() call or calls, as a few drupal functions access things in the main database and calling l() can cause all manner of fun errors if you’ve not switched back yet.

    Comment by Mark Dennehy — February 6, 2008 @ 18:45 | Reply

  2. Hi,
    Is it possible to allow drupal to access different databases? One MySQL and one postgreSQL?

    Comment by architect — May 12, 2009 @ 03:13 | Reply

    • I don’t see why not, just use the DSN to specify one as a mysql:// database and the other as a postgres:// database.

      Comment by Mark Dennehy — May 13, 2009 @ 14:01

  3. Hi,
    It states here http://drupal.org/node/18429

    This only works with two databases of the same type. For example the following code will not work.

    Are you proposing a different process?

    Comment by architect — May 13, 2009 @ 16:36 | Reply

    • No, my error, I missed that caveat.

      Comment by Mark Dennehy — May 13, 2009 @ 16:42


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: