Home >Backend Development >PHP Tutorial >Yii learning summary data access object (DAO), yiidao_PHP tutorial
Yii provides powerful database programming support. Yii Data Access Object (DAO) is built on the PHP Data Object (PDO) extension, allowing access to different database management systems (DBMS) through a single unified interface. Applications developed using Yii's DAO can easily switch to use different database management systems without modifying the data access code.
Data Access Object (DAO) provides a common API for accessing data stored in different database management systems (DBMS). Therefore, when changing the underlying DBMS to another, there is no need to modify the code that uses DAO to access data.
Yii DAO is built on PHP Data Objects (PDO). It is an extension that provides unified data access for many popular DBMS, including MySQL, PostgreSQL, etc. Therefore, to use Yii DAO, the PDO extension and specific PDO database driver (such as PDO_MYSQL) must be installed.
Yii DAO mainly includes the following four categories:
CDbConnection: Represents a database connection.
CDbCommand: Represents a SQL statement executed through the database.
CDbDataReader: Represents a forward-only stream of rows from a query result set.
CDbTransaction: Represents a database transaction.
Below, we introduce the application of Yii DAO in different scenarios.
1. Establish database connection
To establish a database connection, create a CDbConnection instance and activate it. Connecting to a database requires a data source name (DSN) to specify connection information. A username and password may also be used. When an error occurs while connecting to the database (for example, wrong DSN or invalid username/password), an exception will be thrown.
The format of the DSN depends on the PDO database driver used. In general, the DSN contains the name of the PDO driver, followed by a colon, followed by driver-specific connection syntax. Check out the PDO documentation for more information. Below is a list of commonly used DSN formats.
Since CDbConnection inherits from CApplicationComponent, we can also use it as an application component. To do this, configure a db (or other name) application component in the application configuration as follows:
Then we can access the database connection through Yii::app()->db. It is automatically activated unless we specifically configure CDbConnection::autoConnect to false. This way, this single DB connection can be shared in many places in our code.
2. Execute SQL statement
After the database connection is established, SQL statements can be executed by using CDbCommand. You create a CDbCommand instance by calling CDbConnection::createCommand() with the specified SQL statement as argument.
A SQL statement will be executed through CDbCommand in the following two ways:
execute(): Execute a non-query SQL statement, such as INSERT, UPDATE and DELETE. If successful, it returns the number of rows affected by this execution.
query(): Execute a SQL statement that returns several rows of data, such as SELECT. If successful, it returns a CDbDataReader instance through which the resulting rows of data can be iterated. For simplicity, (Yii) also implements a series of queryXXX() methods to directly return query results.
If an error occurs while executing the SQL statement, an exception will be thrown.
3. Get query results
After CDbCommand::query() generates a CDbDataReader instance, you can obtain rows in the result by repeatedly calling CDbDataReader::read(). You can also use CDbDataReader in PHP's foreach language construct to retrieve data row by row.
Note: Unlike query(), all queryXXX() methods will return data directly. For example, queryRow() returns an array representing the first row of the query results.
4. Using transactions
When an application executes several queries, each of which reads information from and/or writes information to the database, it is important to ensure that the database does not leave several queries behind while only executing others. Transactions, represented in Yii as CDbTransaction instances, may be initiated in the following situations:
Start transaction.
Execute queries one by one. Any updates to the database are not visible to the outside world.
Commit the transaction. If the transaction succeeds, the update becomes visible.
If one of the queries fails, the entire transaction is rolled back.
The above workflow can be implemented through the following code:
5. Binding parameters
To avoid SQL injection attacks and improve the efficiency of repeatedly executing SQL statements, you can "prepare" a SQL statement with optional parameter placeholders. When the parameters are bound, these placeholders will be replaced with actual parameters.
Parameter placeholders can be named (appear as a unique token) or unnamed (appear as a question mark). Call CDbCommand::bindParam() or CDbCommand::bindValue() to replace these placeholders with actual parameters. These parameters do not need to be enclosed in quotes: the underlying database driver takes care of this for you. Parameter binding must be completed before the SQL statement is executed.
Methods bindParam() and bindValue() are very similar. The only difference is that the former uses a PHP variable to bind the parameter, while the latter uses a value. For those parameters with large data blocks in memory, for performance reasons, the former should be used first.
For more information about binding parameters, please refer to the relevant PHP documentation.
6. Binding columns
You can also use PHP variables to bind columns when getting query results. This will automatically fill in the latest value every time a row in the query results is obtained.
7. Use table prefixes
Starting from version 1.1.0, Yii provides integrated support for using table prefixes. The table prefix refers to a string added in front of the name of the data table in the currently connected database. It is often used in shared server environments, where multiple applications may share the same database and use different table prefixes to distinguish them from each other. For example, one application can use tbl_ as a table prefix while another can use yii_.
To use a table prefix, configure the CDbConnection::tablePrefix property to the desired table prefix. Then, use {{TableName}} to represent the name of the table in the SQL statement, where TableName refers to the table name without the prefix. For example, if the database contains a table named tbl_user, and tbl_ is configured as the table prefix, then we can use the following code to perform user-related queries: