switching database during runtime

I have a small question…

When I put in a controller code “$connection = new CDbConnection($dsn,‘root’,’’);”


The database does not switch and page loads from the older database (that initially is configured in main config), despite that I have written that “$connection = new CDbConnection($dsn,‘root’,’’);”

Is it possible to somehow write something like Yii::app()->db = new CDbConnection([…])

or something to tell Yii:app() application to change its database for current user???

I need to tell the script that it should use a different database…

This works for me:

  • add to the config new database connection:


// connection params


later (for example in controller):

$db1 = Yii::app()->db1;

if ($db1->active !== FALSE) {

// do something


and: http://www.yiiframework.com/doc/guide/database.dao

Thank you very much for your response.

Well I cannot use a writing to main config file because these databases would be "dynamic". All I need is the possibility to create a new database connection using a $database_name that I provide.

I am making a website with multiple front ends. For each user to have his own front end I need to provide him with a separate database. Database name is made out of his username+dtb for example "user222_dtb". I resolve a username from URL and find out which database needs to be loaded. Now I need to create new connection at runtime, but it seems, that Yii ignores is. I call new connection in the controller that should load an index page, but Yii doesnt pay attention and still loads data from the default database (which is in config).

The solution:

        $dbname = 'differentdatabase';

        $db = Yii::createComponent(array(

           'class' => 'CDbConnection',

            // other config properties...



                'password'=> DB_PWD,


                'emulatePrepare' => true,


                'enableProfiling' => true,


        Yii::app()->setComponent('db', $db);