Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Yii: Database connect in runtime

I would like to connect to a second database with Yii at runtime. The database name would come from a database table after the user to login.

I saw in a tutorial I should do this:

$db2 = Yii::createComponent(array(
    'class' => 'EMongoClient',
    'server' => 'mongodb://127.0.0.1:27017',
    'db' => $emp['database']
));

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

But in my controler when I access Yii::app()->db2 get the error:

Property "CWebApplication.db2" is not defined

What am I doing wrong?

like image 442
Leonardo Delfino Avatar asked Jan 25 '26 16:01

Leonardo Delfino


1 Answers

The following works for me:

Yii::app()->mongodb->setActive(false);
Yii::app()->mongodb->setServer('mongodb://localhost:27017');
Yii::app()->mongodb->setDb('db1');
Yii::app()->mongodb->setActive(true);
like image 186
Daniel Galvan Avatar answered Jan 28 '26 06:01

Daniel Galvan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!