Can I put variable_get in settings.php to load DB settings dynamically or there is a better way.

3 Answers 3


You can use Database::addconnectionInfo() to define a new connection at runtime, like this:

Database::addConnectionInfo('extradb', 'master', array(
  'database' => 'mydb',
  'username' => 'myname',
  'password' => 'mypass',
  'host' => 'localhost',
  'port' => '',
  'driver' => 'mysql',
  'prefix' => '',

You can then use db_set_active('extradb') to switch to it.

  • That code is not tested, by the way, just an example of what I believe should work from reading database.inc. Mar 18, 2013 at 14:37
  • The constants in the code can be replaced by variables from variable_get(); You'll need to call this code, which can be placed in a suitable function, before you use the secondary database in your own code. Mar 18, 2013 at 19:45

Drupal allows you to override settings using the $conf[] array in settings.php. They will be then available via variable_get('key', 'default') in any module.

See 'defining site variables' and variable_get()

The pattern we use is that any defaults go into install.php. starts with:

function hottopicsnotify_install() {
  variable_set(HOTTOPICSNOTIFY_CONTENT_TYPES_VAR, 'hottopics_node_form');

Override the variables with an admin form where needed. e.g.

function hottopics_settings($form, &$form_state) {

Read using variable_get. e.g.:

'#default_value' => variable_get(HOTTOPICSNOTIFY_EDITORIAL_CRON_KEY, ''),
  • I know variable_get(), but my question is whether is it possible to use this function in the settings.php file or not ? Mar 17, 2013 at 14:17
  • No, the settings file is meant to set configuration values. At this point variable_get() is not available. What are you trying to achieve? Mar 17, 2013 at 15:47
  • You can only override values in settings. It is for setting. The way to read is variable_get. Are you trying to make a global? How are you planning on using the variable?
    – Interlated
    Mar 18, 2013 at 1:44
  • @AlfredArmstrong I'm trying to make the connection to the DB flexible like the host name of the secondary DB comes from admin settings form ? Mar 18, 2013 at 10:27
  • @Interlated I plan to load my secondary DB credential dynamically from admin settings form ? Mar 18, 2013 at 10:41

Have a look at


You can switch the the active database connection that way.

Define the databases in settings.php, then switch to one with

db_set_active('legacy'); // example
// Query stuff using DB API

and switch back to default with


It's also possible to define the database connection later in code, but hopefully db_set_active will suffice.

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.