How To Connect Multiple Databases in Drupal

0
Your rating: None

Sometimes we need to connect to third-party or legacy databases,and it would be great to use Drupal’s database API for doing this.

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';

But while using an array, the key is a shortcut name you will refer to while activating the data-base 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://user:password@localhost/drupal5';
$db_url['legacy'] = 'mysql://user:password@localhost/legacydatabase';

When you need to connect to one of the other databases 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.
db_set_active('legacy');
$result = db_query("SELECT * FROM ldap_user WHERE uid = %d", $user->uid);
// Switch back to the default connection when finished.
db_set_active('default');

Make sure to always switch back to the default connection.

Since the database abstraction layer is designed to use identical function names for
each database, multiple kinds of database back-ends (e.g., both MySQL and PostgreSQL)
cannot be used simultaneously. For further reference, check http://drupal.org/node/19522 on how to allow both MySQL and PostgreSQL connections from within the same site.

Post new comment

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Copy the characters (respecting upper/lower case) from the image.

Cumulus Tag Cloud

Kiran Says

SEO Architect,SEO Specialist reflect my values.

By enduring black hat methods the SEO industry is setting itself up for washout and sleepwalking into oblivion.

Jobs in India