db_set_active

Versions
4.6 – 6
db_set_active($name = 'default')
7
db_set_active($key = 'default')

Activate a database for future queries.

If it is necessary to use external databases in a project, this function can be used to change where database queries are sent. If the database has not yet been used, it is initialized using the URL specified for that name in Drupal's configuration file. If this name is not defined, a duplicate of the default connection is made instead.

Be sure to change the connection back to the default when done with custom code.

Parameters

$name The name assigned to the newly active database connection. If omitted, the default connection will be made active.

Related topics

Code

includes/database.inc, line 98

<?php
function db_set_active($name = 'default') {
  global $db_url, $db_type, $active_db;
  static $db_conns;

  if (!isset($db_conns[$name])) {
    // Initiate a new connection, using the named DB URL specified.
    if (is_array($db_url)) {
      $connect_url = array_key_exists($name, $db_url) ? $db_url[$name] : $db_url['default'];
    }
    else {
      $connect_url = $db_url;
    }

    $db_type = substr($connect_url, 0, strpos($connect_url, '://'));
    $handler = "includes/database.$db_type.inc";

    if (is_file($handler)) {
      include_once($handler);
    }
    else {
      die('Unsupported database type');
    }

    $db_conns[$name] = db_connect($connect_url);

  }
  // Set the active connection.
  $active_db = $db_conns[$name];
}
?>
Login or register to post comments
 
 

All source code and documentation on this site is released under the terms of the GNU General Public License, version 2 and later. Drupal is a registered trademark of Dries Buytaert.