Dynamic DB Connection

I’m starting a new development.

I have multiple clients (companies) and each client has multiple users.

Each client has their own database, so during user authentication, I discover the name of associated database for that user.

The structure of each database is identical… only the data is different.

The number of clients (and therefor the number of databases) is unknown when the application is written, so it is not possible to include all the connections in the bootstrap script.

Now, what I want to do is, dynamically alter the DB connection that is in the bootstrap or have the ability to dynamically create a new connection for the user signing in. Is there a simple solution for this in Yii and still use AR?

Hi, did someone ask to your question or you found the solution for that?

Because i would like to do something similar…



No, I never received a response. As a result, I decided to use a different framework (QCubed), where there are more users and assistance is more readily available.

You can override CActiveRecord::getDbConnection like the following:

    public function getDbConnection()



            return self::$db;



            // create DB connection based on your spec here:

            // self::$db=new CDbConnection(...);

            // self::$db->active=true;

            // return self::$db;



Alll your AR classes should then extend this new base class.

Ok, i can extend getDbConnection…but can you give me an example of what i can do?

For example… if i have 4 db connections: db1 , db2 ,db3 and db4.

How can i set dinamically which database connection to use?

Thanks so much

I found this way:

abstract class NewDbConnection extends CActiveRecord


private $db_connection='db';

public function getDbConnection()


    print "--->".$this->db_connection."<br>";

    $db = Yii::app()->{$this->db_connection};


    return $db;


public function setDbConnection($c)



    print "X----->".$this->db_connection."<br>";



It works,

the only issue is that i have to initialize db_connection because getDbConnection is called at model creatin so it need to be a valid database connection that contains the table associated with the model.

Am i correct?