Drupal - How to define and use an external database connection in a custom module

There's no particular place to put this code (hook or module), you just put it where you need it.
So it should go just before your queries on the other database and just after to set back the default DB.

If all your module will rely on the external DB just put it a the beginning of the first function called for your module and at the end of the last function.

Of course every one of your function should be executed on the external DB and nothing must have to query the default database without switching back.

This following code would fail:

db_set_active('YourDatabaseKey');

$result = db_query('SELECT ...'); //Your own queries on the external DB.

$node = node_load(123); //This would fail on the external DB.

$result = db_query('SELECT ...'); //Your own queries on the external DB.

db_set_active(); 

You should switch back and forth:

db_set_active('YourDatabaseKey');

$result = db_query('SELECT ...'); //Your own queries on the external DB.

db_set_active(); 
$node = node_load(123); //Query made on the default Drupal DB.
db_set_active('YourDatabaseKey');

$result = db_query('SELECT ...'); //Your own queries on the external DB.

db_set_active(); 

You will have to add into settings.php located at /sites/default/ in following syntax

//Drupal 6

$db_url['default'] = 'mysql://db_user:password@localhost/db_name';
$db_url['external'] = 'mysql://db_user2:password@localhost/db_name2';

//Drupal 7

$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'db1',
      'username' => 'user1',
      'password' => 'pass',
      'host' => 'host1',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
  'extra' =>
  array (
    'default' =>
    array (
      'database' => 'db2',
      'username' => 'user2',
      'password' => 'pass',
      'host' => 'host2',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

And after these settings you can use db_set_active() to switch between databases.

Tags:

Database

7