0

Does anyone know of a way in which I can add an extra database connection field to the yii configuration file after I've successfully logged in a user to my site?

We've got a global System Database where we configure our users and save a field with their database name. I would like to create another connection to that database after authenticating the user. Thus referencing it like Yii::app()->clientDB. Is this possible?

Every client on our system have their own respective database with tables.

2 Answers 2

1

You can achieve it by this code (not tested, but should work):

$connection = new CDbConnection($dsn, $username, $password);
$connection->active = true;
Yii::app()->setComponent('clientDB', $connection);
Sign up to request clarification or add additional context in comments.

Comments

1

Yes you can. In your config file it would look like:

'db'=>array(
        'connectionString' => 'mysql:host=hostIP;port=3306;dbname=database1',
                    'class'=>'CDbConnection',
        'emulatePrepare' => true,
        'username' => 'username1',
        'password' => 'password1',
        'charset' => 'utf8',
    ),
            'db2'=>array(
        'connectionString' => 'mysql:host=hostIP2;port=3306;dbname=database2',
                    'class'=>'CDbConnection',
        'emulatePrepare' => true,
        'username' => 'username2',
        'password' => 'password2',
        'charset' => 'utf8',
    ),

db would be the default database. Whenever you want to switch you would write this in the controller:

$connection->Yii::app()->db2;
//then you would pass the connection into whatever you are using for your queries.
//For example for an raw SQL command:
$command=$connection->createCommand($sqlQuery);
$command->execute();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.