In my Yii2 (basic application) web.php I configure a NULL db connection as 2nd database connection.
This needs to be filled with valid parameters which are coming from a record on the main db connection:
'db' => require(__DIR__ . '/db.php'),
'db2' => [
'class' => 'yii\db\Connection',
'dsn' => NULL,
'username' => NULL,
'password' => NULL,
'charset' => 'utf8',
],
After initializing the app() i need to fill out the NULL parameters with values that i retrieve from another database to further use it in models.
How can i achieve this in Yii2?
No problem, it is supported
\Yii::$app->db2->close(); // make sure it clean
\Yii::$app->db2->dsn= 'yourdsn';
\Yii::$app->db2->username = 'username';
\Yii::$app->db2->password = 'password';
Done, now you can use it
Yii::$app->db2->...
Another way:
$connection = new \yii\db\Connection([
'dsn' => $dsn,
'username' => $username,
'password' => $password,
]);
$connection->open();
$command = $connection->createCommand('SELECT * FROM post')->....;
Refer: http://www.yiiframework.com/doc-2.0/yii-db-connection.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With