Connecting to Multiple Databases

While it's easy to use

\Database::connection()

to retrieve the current global Concrete CMS database connection – what if you want to work with multiple databases in custom code you're writing? It's easy and recommended that you simply add custom business database tables into your Concrete database (which you can then access via Database::connection()), but what if you have a legacy database that you can't just migrate into the Concrete database? You'll need an additional database connection.

Fortunately, this is easy to accomplish with some custom configuration. Normally, in your application/config/database.php file you'll have a single "concrete" database connection that might look something like this:

return array(
    'default-connection' => 'concrete',
    'connections' => array(
        'concrete' => array(
            'driver' => 'c5_pdo_mysql',
            'server' => 'localhost',
            'database' => 'database',
            'username' => 'testuser',
            'password' => 'testpassword',
            'charset' => 'utf8',
        )

    ),
);

Just add another entry to the connections array. If your legacy database is responsible for storing "pricing" data, you could name it "pricing":

return array(
    'default-connection' => 'concrete',
    'connections' => array(
        'concrete' => array(
            'driver' => 'c5_pdo_mysql',
            'server' => 'localhost',
            'database' => 'database',
            'username' => 'username',
            'password' => 'password',
            'charset' => 'utf8',
        ),
        'pricing' => array(
            'driver' => 'c5_pdo_mysql',
            'server' => 'secure-pricing.wherever.com',
            'database' => 'pricing_db',
            'username' => 'username',
            'password' => 'password',
            'charset' => 'utf8',
        ),
    ),
);

Then, anywhere you'd normally connect via this method:

$db = \Database::connection();

Just connect like this:

$db = \Database::connection('pricing');

for your custom queries. That's it!