How to create and access multiple database in Drupal 7
Accessing multiple database in Drupal 7 is easy by now. We can attach more than one database inside drupal 7. Good news, we can attach database that custom made ( not drupal 7 structure database ). Also, we can switch to another database easily. In this example, you have two database : drupal7 and custom database called custom. So here are steps :
1. Edit settings.php in sites/default
<?php
$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. Accessing multiple database in Drupal 7 module or themes
Drupal 7 using default configuration while running. So, if we want to access custom database, we need to switch into another configuration. We can use db_set_active() for switching. Here are example :
<?php
db_set_active('custom');
$result = db_query("SELECT nid, title, created, changed, promote, sticky, vid FROM {node} ORDER BY created ASC LIMIT 0, 10");
// This result querying from custom database
db_set_active('default');
$result = db_query("SELECT nid, title, created, changed, promote, sticky, vid FROM {node} ORDER BY created ASC LIMIT 0, 10");
// This result querying from default database drupal 7
?>Now, we can also attach database from wordpress, cakePHP or another non-drupal 7.
Comments
Rubjo (not verified)
Tue, 02/08/2011 - 16:16
Permalink
This really helped me, thanks
This really helped me, thanks :)
Dror (not verified)
Tue, 07/05/2011 - 16:33
Permalink
not clear where to add the 2nd code
Hi there,
sorry for bother you.
however, im new to drupal but have a bit of knowledge of PHP programing,
i'm trying to migrate D6 DB to D7, nad it is nbot clear to me where to add the 2nd code in order to have multiply connection and to the D6 Database.
if you could advise where should i add the 2nd code.
thanks in advanced.
admin
Mon, 07/11/2011 - 15:00
Permalink
2nd code placed
You can place 2nd in themes or your modules.
stwe (not verified)
Tue, 07/12/2011 - 04:38
Permalink
thanks!
thanks you to the tutorial! it's really helpfull
admin
Fri, 07/15/2011 - 13:38
Permalink
Glad it's helping you
Glad it's helping you
jayendra (not verified)
Tue, 11/08/2011 - 16:37
Permalink
thanks
hi,
Thanks to share this information.
mimi (not verified)
Thu, 05/03/2012 - 04:16
Permalink
How can I get the query result from custom table?
My code is :
db_set_active('custom');
$result=db_query('SELECT customerName from customers');
foreach ($result as $row)
$output.=$row->customerName;
--------
it give me error as follows:
Notice: Undefined property: stdClass::$customerName in menufun_hello()
Add new comment