Yii2 How to establish connection to MySQL/MariaDB database

  • Last update: Apr 3, 2024
  • Views: 65
  • Author: Admin
Yii2 How to establish connection to MySQL/MariaDB database

Colleagues hello to all.

In today's article, we'll talk about how to connect to a Mysql or Mariadb database in Yii2. Before connecting to a database, you must have the  PDO extensions and the PDO driver installed on your server. For example, to connect to a Mysql database, you must have the  pdo_mysql driver installed. For database connections Mariadb driver pdo_mysql is also suitable.

 

In Yii2, the db.php file, which is located in the config/db.php directory, is responsible for connecting to the database

yii2 connect to database

The image shows the location of the file that is responsible for connecting to the database.


 

The class yii\db\Connection is responsible for database connections in Yii2.

yii2 connect to database

This file will return an array with parameters for connecting to the database.

return [
    'class' => 'yii\db\Connection',
    'dsn' => 'mysql:host=192.168.4.10;dbname=inzhener',
    'username' => 'root',
    'password' => 'Qwerty123',
    'charset' => 'utf8',
];

Parameter descriptions:

  • class - database connector class.
  • dsn - here we need the ip or hostname of the server where the database is installed.
  • username - user account in the database.
  • password - Password for the account in the database.
  • charset - encoding used in the database.

There are many more parameters such as a prefix before the database name or maybe we want to enable caching and so on, but in order to establish connections to the database, the parameters that I specified will suffice.


 

Thank you all, I hope that my article helped you in some way.

 

SIMILAR ARTICLES