Jump to Navigation

064 - Connecting to Multiple Database within Drupal

In the settings.php file, $db_url can be either a string (as it usually is) or an array composed of multiple
database connection strings.

Here's the default syntax, specifying a single connection string :

$db_url = 'mysql://username:password@localhost/databasename';

When using an array, the key is a shortcut name you will refer to while activating the database connection, and
the value is the connection string itself.

Here's an example where we specify two connection strings, default and legacy:

$db_url['default'] = 'mysql://username:password@local/defaultDB';
$db_url['legacy'] = 'mysql://user:password@localhost/legacyDB';

When you need to connect to one of the other database in Drupal, you activate it by its key name and
switch back to the default connection when finished.

// Get some information from a non-Drupal database.

$result = db_query("SELECT * FROM ldap_user WHERE uid = %d", $user->uid);

// Switch back to the default connection when finished.




Main menu 2

Story | by Dr. Radut