How to create and access multiple database in Drupal 7

While developing a website, you may want to use multiple databases. Its very easy in Drupal 7 to use multiple databases. Here are the steps:
1. Edit settings.php in sites/default
$databases = array (
'default' =>
array (
'default' =>
array (
'database' => 'drupal7',
'username' => 'root',
'password' => '<your-password>',
'host' => 'localhost',
'port' => '',
'driver' => 'mysql',
'prefix' => '',
),
),'custom' =>
array (
'default' =>
array (
'database' => 'custom',
'username' => 'root',
'password' => '<your-password>',
'host' => 'localhost',
'port' => '',
'driver' => 'mysql',
'prefix' => '',
)
)
);
2. After making these changes, you can access different database:
db_set_active('custom');
$result = db_query("SELECT nid, title FROM {node} LIMIT 0, 10");
// This result querying from custom database

db_set_active('default');
$result = db_query("SELECT nid, title FROM {node} LIMIT 0, 10");
// This result querying from default database drupal 7
Farhamdani

Sharing insights on tech, blogging, and passive income. Follow for more at farhamdani.eu.org!

Drop your comments, but make sure they’re related to the discussion!

I'd be grateful if you could read the Commenting Rules on this blog before posting a comment.

Post a Comment (0)
Previous Post Next Post