To connect to multiple databases in the Yii2 framework, you need to do the following:
1. Create two database configuration files in your site’s config. I keep the connections in separate files, and they look like this (example).
Connection to the first database:
return [ 'class' => 'yiidbConnection', 'dsn' => 'mysql:host=127.0.0.1;dbname=work_db1', 'username' => 'root', 'password' => '', 'charset' => 'utf8', 'tablePrefix' => 'tbl_', ];
Connection to the second database:
return [ 'class' => 'yiidbConnection', 'dsn' => 'mysql:host=127.0.0.1;dbname=work_db2', 'username' => 'root', 'password' => '', 'charset' => 'utf8', 'tablePrefix' => 'tbl_', ];
2. In the main config file, register both connections:
'db' => require(__DIR__ . '/db.php'), 'db2' => require(__DIR__ . '/db2.php'),
Retrieve data from the database using a SQL query:
$Query = (new yiidbQuery());
$Command = Yii::$app -> db2;
$data_ar = $Command -> createCommand(
$Query -> select('*')
-> from('{{%authitem}}')
-> createCommand()
-> getRawSql()
)
-> queryAll();
echo"<pre>";print_r($data_ar);echo"</pre>";