Connect to multiple database in Yii framework

Yii configuration file protected/main/config.php by default comes up with one db connection. To have multiple db connections like, same db withing mysql or sqlite or something else, then do follow the below code

<?php
// protected/main/config.php
return array(
    ...
    'components' => array(
        // connection one
        'db' => array(
            'connectionString' => 'mysql:host=dbserver1;dbname=my1db',
            ...
        ),
        // connection two
        'dblogs' => array(
            'connectionString' => 'mysql:host=logshost;dbname=logs',
            'username'         => 'loguser',
            'password'         => '*******',
            ...
            'class'            => 'CDbConnection'          // Important! DO NOT FORGET THIS!
        ),
        ...
?>

If you notice the dblogs has class as CDbConnection, which is used for connection purpose. Internally, Yii assigns CDbConnection class to db by default.

How to use: You can use the second database using Yii::app()->dblogs and first by Yii::app()->db.

We can also connect to db as shown below

<?php
$connection=new CDbConnection($dsn,$username,$password);
// establish connection. Check for try and catch for errors
$connection->active=true;
.......... do your stuff here
$connection->active=false;  // close connection
?>

Leave a Reply