Thursday, May 19, 2016

Connect to multiple databases in Drupal 7 ?

The way Drupal is designed, it handle most of the user demands, sometime most complex one. Here we are discussing the having multiple databases connection in, and i am very much sure that drupal can do it with easy way. More Details

There are two way we can achieve this.
  • Adding database in settings.php file
  • Adding in module as needed (on the fly)

Adding database in settings.php file

You can add your database in settings.php so that all module can use it.  here is sampe, suppose we have new databses "second_db"
$databases = array();
$databases['default']['default'] = array(
  // Drupal's default credentials here.
  // This is where the Drupal core will store its data.
);
$databases['second_db']['default'] = array(
  // Your secondary database's credentials here.
  // You will be able to explicitly connect to this database from your modules.
);

Here is the way we can access this in our module
// Use the database we set up earlier
db_set_active('second_db');
// Run some queries, process some data
// ...

// Go back to the default database,
// otherwise Drupal will not be able to access its own data later on.
db_set_active();

Adding in module as needed (on the fly)

This is used when a single module needs new database  In this case we can desfine our databse connection directly in our module like this.
 $other_database = array(
      'database' => 'databasename',
      'username' => 'username', // assuming this is necessary
      'password' => 'password', // assuming this is necessary
      'host' => 'localhost', // assumes localhost
      'driver' => 'mysql', // replace with your database driver
  );
  // replace 'YourDatabaseKey' with something that's unique to your module
  Database::addConnectionInfo('YourDatabaseKey', 'default', $other_database);
  db_set_active('YourDatabaseKey');

  // execute queries here

  db_set_active(); // without the paramater means set back to the default for the site
  drupal_set_message(t('The queries have been made.'));

No comments:

Post a Comment