Yii2.0 Database Connection

Yii2.0 Database Connection
To use the database we have to configure the database connection component by adding ‘db’ information to application config/main.php file.

Yii 2.0 DBMS Supports

Yii 2.0 supports the following DBMS:

DBMS Configuration

Create a ‘db.php’ file inside the config folder and add the database credentials like below code.

return [
	'class' => 'yii\db\Connection',
    'dsn' => 'mysql:host=localhost;dbname=reportsa_macromoney', // MySQL, MariaDB
    //'dsn' => 'sqlite:/path/to/database/file', // SQLite
    //'dsn' => 'pgsql:host=localhost;port=5432;dbname=mydatabase', // PostgreSQL
    //'dsn' => 'cubrid:dbname=demodb;host=localhost;port=33000', // CUBRID
    //'dsn' => 'sqlsrv:Server=localhost;Database=mydatabase', // MS SQL Server, sqlsrv driver
    //'dsn' => 'dblib:host=localhost;dbname=mydatabase', // MS SQL Server, dblib driver
    //'dsn' => 'mssql:host=localhost;dbname=mydatabase', // MS SQL Server, mssql driver
    //'dsn' => 'oci:dbname=//localhost:1521/mydatabase', // Oracle
    'username' => 'root',
    'password' => '$123',
    'charset' => 'utf8',

We have to add this file into $config[‘components’][‘db’] params to make a DB connection. For example, Add the following line into ‘config/main.php’ file.

'components' => [    
		'db'=>require(__DIR__ . '/db.php'),

Now the database connection will created.
After the connection was created, we can access the ‘db’ connection like

$connection = \Yii::$app->db;
$secondaryConnection = \Yii::$app->secondDb;