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.
- Techdipu's blog
- 1171 reads













Post new comment