Multiple databases in Drupal

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:
[ccN lang=”php”]$db_url[‘default’] = ‘mysql://drupal:drupal@localhost/drupal’;
$db_url[‘mydb’] = ‘mysql://user:pwd@localhost/anotherdb’;
$db_url[‘db3’] = ‘mysql://user:pwd@localhost/yetanotherdb’;[/cc]
And then to use:
[ccN lang=”php”]db_set_active(‘mydb’);
db_query(‘SELECT * FROM table_in_anotherdb’);
//Switch back to the default connection when finished.
db_set_active(‘default’);[/cc]

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

5 thoughts on “Multiple databases in Drupal

  • Feb 6, 2008 at 1845
    Permalink

    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.

  • May 12, 2009 at 0313
    Permalink

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

  • May 13, 2009 at 1401
    Permalink

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

  • May 13, 2009 at 1636
    Permalink

    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?

  • May 13, 2009 at 1642
    Permalink

    No, my error, I missed that caveat.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Stochastic Geometry is Stephen Fry proof thanks to caching by WP Super Cache

%d bloggers like this: