Use multiple / external databases in Drupal 8

Submitted by editor on Wed, 06/29/2016 - 11:40
Question

How to connect to multiple databases within Drupal 8 ?

How to use multiple databases with Drupal 8 ?

The database settings (and connection) has 3 levels.

1. KEY
2. TARGET
3. DATA

Example:

$databases[KEY][TARGET] = array (
 DATA
);

Like:

$databases['default']['default'] = array (
  'database' => 'drupal8_default_db',
  ....
);

 

Methode 1. Multiple connections Using Different "KEY" (Recommended)

1. Configure your drupal instance for multiple databases (setting.php)

'key' is the first level of the database connection;

Example :

$databases['default']['default'] = array (
  'database' => 'drupal8_default',
  'username' => 'root',
  'password' => 'root',
  'prefix' => '',
  'host' => 'localhost',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);

$databases['myseconddb']['default'] = array (
  'database' => 'mysql',
  'username' => 'root',
  'password' => 'root',
  'prefix' => '',
  'host' => 'localhost',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);

2. Connect to the correct data base:

Example:

//To get the default database
$con = \Drupal\Core\Database\Database::getConnection();
//To get another database (here : 'myseconddb')
$con = \Drupal\Core\Database\Database::getConnection('default','myseconddb');

 

Methode 2. Multiple connections Using Different "TARGETS" (Not recommended, Use for master/slave configuration)

1. Configure your drupal instance for multiple databases (setting.php)

'target' is the second level of the database connection;

Example :

$databases['default']['default'] = array (
  'database' => 'drupal8_default',
  'username' => 'root',
  'password' => 'root',
  'prefix' => '',
  'host' => 'localhost',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);

$databases['default']['myseconddb'] = array (
  'database' => 'mysql',
  'username' => 'root',
  'password' => 'root',
  'prefix' => '',
  'host' => 'localhost',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);

2. Connect to the correct data base:

Example:

//To get the default database
$con = \Drupal\Core\Database\Database::getConnection();
//To get another database (here : 'myseconddb')
$con = \Drupal\Core\Database\Database::getConnection('myseconddb');

 

And See also How to use database programmatically

 

Database configuration :
https://www.drupal.org/docs/7/api/database-api/database-configuration
Master / Slave Configuration :
https://www.drupal.org/node/1952990

Add new comment