0

Is db_set_active() need to work with a Drupal database or can I use it with a database that doesn't contain any drupal tables ?

1
  • It's not a duplicate question. Here I asked about "how it's work" not about "how to use it". The nuance is important to use it properly.
    – Promo
    Commented Mar 17, 2016 at 9:30

1 Answer 1

2

db_set_active() is used for connecting to another database. The other database does not need to be Drupal at all.

Just don't forget to switch back to default DB when you are done. If you don't, Drupal will try to perform all subsequent queries in the other database, which will result in a lot of errors and potentially mess up the data in the other database.

Here's example code:

// Connect to your other database.
db_set_active('your_other_db');
// Run any queries you want.
db_query("...");
// Switch back to the default database of your installation.
db_set_active();

You can read more about db_set_active() here.

Another note, per Neograph734's reminder: the argument you would pass to the db_set_active() needs to be the same key you used for adding another DB access info in settings.php file.

Here's an example:

$databases = array (
  'default' => array (
    'default' => array (
      'database' => 'your_default_database',
      'username' => 'username',
      'password' => 'password',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
  'your_other_db' => array (
    'default' => array (
      'database' => 'your_other_database',
      'username' => 'username',
      'password' => 'password',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);
1
  • Thank you, your first sentence answers the question because in the documentation never talks about database format :)
    – Promo
    Commented Mar 17, 2016 at 9:28

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