0

Following situation: I have a multisite with several sites. The codebase is the same but every site has his own database. Now i'm creating a module where i want to make adjustments in the databases for all sites at the same time. So i have to be able to make database connections to the other sites.

I already was able to get the settings from the other sites with that:

$sites = glob(DRUPAL_ROOT . DIRECTORY_SEPARATOR . 'sites' . DIRECTORY_SEPARATOR . '*', GLOB_ONLYDIR);

foreach ($sites as $site) {
  $site_path = str_replace(DRUPAL_ROOT, '', $site);
  $siteName = str_replace('/sites/', '', $site_path);

  if (is_readable($site . '/settings.php')) {
    $siteConfigs[$siteName] = [];
    $settings = [];
    $databases = [];
    $app_root = DRUPAL_ROOT;

    require $site . '/settings.php';
    $siteConfigs[$siteName]['settings'] = new Settings($settings);
    $siteConfigs[$siteName]['databases'] = $databases;
  }
} ```

How can i use DB Connection of another site on my multisite installation? I tried different things like:

foreach ($siteConfigs as $siteConfig) {
  Database::addConnectionInfo('default', 'default', $siteConfig['databases']['default']['default']);
  $db = Database::getConnectionInfo();
  var_dump($db);

}

But it always returns just the current site.

Thanks for any advice!

1

You can initialize multiple database connections like this in your settings.php file:

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

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

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

Then you can get the connections with your module etc.:

<?php
$greenSiteDatabase = Database::getConnection('default', 'green-site');
$yellowSiteDatabase = Database::getConnection('default', 'yellow-site');
$defaultDatabase = Database::getConnection('default', 'default');

You can query a database like so:

$banana = $yellowSiteDatabase->select('SomeTable', 'st')
  ->fields('st', ['fruit'])
  ->condition('fruit', $someCode)
  ->execute()
  ->fetchObject();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.