I need to connect to my database in php file in drupal 7. Each time I move from local server to development server, I have to change my db and host. I have seen setting.php file which have array of database.

$databases = array (
  'default' => 
  array (
    'default' => 
    array (
      'database' => 'my_db',
      'username' => 'root',
      'password' => '',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',

How do I aceess this database array in drupal 7 to use it connecting to database

$con = mysqli_connect('localhost','root','','my_db');

Thanks for Help

  • First of all it's a bad practice to connect to Mysql Using mysqli_connect inside drupal that too in php file... You might need to explain why you are using .php file inside and what you trying to achieve..
    – Anil Sagar
    Commented Mar 28, 2014 at 4:15

1 Answer 1


If you want to access the Drupal database from a standalone script.

Firstly, consider if you can put the PHP code in a Drupal module instead.
Secondly, consider bootstrapping Drupal in your PHP script

 * Root directory of Drupal installation.
define('DRUPAL_ROOT', '/var/www/drupal');

// Bootstrap to database level for db api
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';

You can then use the Drupal database API to query content from the Drupal database.

Thirdly, if connecting to a different database is required, consider defining the other database in settings.php and switching to a target database using db_set_active

// Settings.php
$databases['default']['default'] = array(
  'driver' => 'mysql',
  'database' => 'drupal7',
  'username' => 'drupal_user',
  'password' => 'drupal_password',
  'host' => 'localhost',
  'prefix' => '',

$databases['other_database']['default'] = array(
  'driver' => 'mysql',
  'database' => 'other_database',
  'username' => 'other_database_user',
  'password' => 'other_database_password',
  'host' => 'localhost',
  'prefix' => '',

Then you can switch between databases with db_set_active

// Query other database
// $query = db_select('my_table'); // e.g
// Return to default database
  • while switching between database, Do I have to come back to db_set_active()--> to default database each time ?
    – Hitesh
    Commented Mar 28, 2014 at 4:40
  • Drupal will switch back to the default db at the end of the page execution, use db_set_active() or db_set_active('default') to switch it back manually. Commented Mar 28, 2014 at 9:32
  • Thanks I learnt something !!! thank you so much for answering :)
    – Hitesh
    Commented Mar 28, 2014 at 11:26
  • 1
    This don't answer the question. Is a good answer, but is not what OP is asking. Commented Apr 6, 2018 at 20:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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