Home  >  Article  >  PHP Framework  >  How to connect to the database in yii

How to connect to the database in yii

尚
Original
2019-12-31 16:16:283406browse

How to connect to the database in yii

Yii uses PDO (PHP Date Object) to connect to a variety of databases. Therefore, Yii can provide good support for almost all mainstream databases. This is also the broad applicability that a mature framework should have.

Before performing any operations on the database, a connection must be established with the database server. In the Yii application, there is a dedicated core component for handling database connections. We can easily find it in the configuration file:

'components' => [
    'db' => [
        'class' => 'yii\db\Connection',
        'dsn' => 'mysql:host=localhost;dbname=yii2advanced',
        'username' => 'root',
        'password' => '',
        'charset' => 'utf8',
    ],
    // ... ...],// ... ...

Yii uses yii\db\Connection to represent the database connection. This Connection implements a simple encapsulation of PDO, masks the differences between various databases, and implements a unified development interface.

In this way, you can ignore most database compatibility issues during the programming process and focus more on functional development. For example, you no longer have to worry about not being able to use Money type fields under MySQL, etc.

In yii\db\Connection, there is a $schemaMap array, which is used to establish the mapping relationship between the PDO database driver and the specific schema class:

public $schemaMap = [
    'pgsql' => 'yii\db\pgsql\Schema', // PostgreSQL
    'mysqli' => 'yii\db\mysql\Schema', // MySQL
    'mysql' => 'yii\db\mysql\Schema', // MySQL
    'sqlite' => 'yii\db\sqlite\Schema', // sqlite 3
    'sqlite2' => 'yii\db\sqlite\Schema', // sqlite 2
    'sqlsrv' => 'yii\db\mssql\Schema', // newer MSSQL driver on MS Windows hosts
    'oci' => 'yii\db\oci\Schema', // Oracle driver
    'mssql' => 'yii\db\mssql\Schema', // older MSSQL driver on MS Windows hosts
    'dblib' => 'yii\db\mssql\Schema', // dblib drivers on GNU/Linux (and maybe other OSes) hosts
    'cubrid' => 'yii\db\cubrid\Schema', // CUBRID];

We can think that Yii defaults to It supports 10 DBMSs (6 Schemas) in the above array, which is completely sufficient in most cases. In case you use a DBMS beyond this range, you can write a Schema yourself so that Yii can support the DBMS while ensuring compatibility.

Recommended learning: yii framework

The above is the detailed content of How to connect to the database in yii. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn