Yii learning summary data access object (DAO), yiidao_PHP tutorial

WBOY
Release: 2016-07-13 10:06:33
Original
1121 people have browsed it

Yii Learning Summary Data Access Object (DAO), yiidao

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.

Copy code The code is as follows:

$connection=new CDbConnection($dsn,$username,$password);
// Establish a connection. You can use try...catch to catch exceptions that may be thrown
$connection->active=true;
......
$connection->active=false; // Close connection

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.

Copy code The code is as follows:

SQLite: sqlite:/path/to/dbfile
MySQL: mysql:host=localhost;dbname=testdb
PostgreSQL: pgsql:host=localhost;port=5432;dbname=testdb
SQL Server: mssql:host=localhost;dbname=testdb
Oracle: oci:dbname=//localhost:1521/testdb

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:

Copy code The code is as follows:

array(
 …
'components'=>array(
       …       …
         'db'=>array(
             'class'=>'CDbConnection',
             'connectionString'=>'mysql:host=localhost;dbname=testdb',
              'username'=>'root',
               'password'=>'password',
             'emulatePrepare'=>true, // needed by some MySQL installations
),
),
)

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.

Copy code The code is as follows:

$connection=Yii::app()->db; // Assume you have established a "db" connection
// If not, you may need to explicitly establish a connection:
// $connection=new CDbConnection($dsn,$username,$password);
$command=$connection->createCommand($sql);
// If necessary, this SQL statement can be modified as follows:
// $command->text=$newSQL;

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.

Copy code The code is as follows:

$rowCount=$command->execute(); // Execute no query SQL
$dataReader=$command->query(); // Execute a SQL query
$rows=$command->queryAll(); // Query and return all rows in the result
$row=$command->queryRow(); // Query and return the first row in the result
$column=$command->queryColumn(); // Query and return the first column in the result
$value=$command->queryScalar(); // Query and return the first field of the first row in the result

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.

Copy code The code is as follows:

$dataReader=$command->query();
// Call read() repeatedly until it returns false
while(($row=$dataReader->read())!==false) { ... }
// Use foreach to iterate through each row in the data
foreach($dataReader as $row) { ... }
// Extract all rows into an array at once
$rows=$dataReader->readAll();

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:

Copy code The code is as follows:

$transaction=$connection->beginTransaction();
try
{
$connection->createCommand($sql1)->execute();
$connection->createCommand($sql2)->execute();
//.... other SQL executions
$transaction->commit();
}
catch(Exception $e) // If a query fails, an exception will be thrown
{
$transaction->rollBack();
}

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.

Copy code The code is as follows:

// A SQL
with two placeholders ":username" and ":email" $sql="INSERT INTO tbl_user (username, email) VALUES(:username,:email)";
$command=$connection->createCommand($sql);
// Replace the placeholder ":username" with the actual username
$command->bindParam(":username",$username,PDO::PARAM_STR);
// Replace the placeholder ":email" with the actual Email
$command->bindParam(":email",$email,PDO::PARAM_STR);
$command->execute();
// Insert another row with new parameter set
$command->bindParam(":username",$username2,PDO::PARAM_STR);
$command->bindParam(":email",$email2,PDO::PARAM_STR);
$command->execute();

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.

Copy code The code is as follows:

$sql="SELECT username, email FROM tbl_user";
$dataReader=$connection->createCommand($sql)->query();
// Use the $username variable to bind the first column (username)
$dataReader->bindColumn(1,$username);
// Use the $email variable to bind the second column (email)
$dataReader->bindColumn(2,$email);
while($dataReader->read()!==false)
{
// $username and $email contain the username and email in the current line
}

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:

Copy code The code is as follows:

$sql='SELECT * FROM {{user}}';
$users=$connection->createCommand($sql)->queryAll();

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/959100.htmlTechArticleYii Learning Summary Data Access Object (DAO), yiidao Yii provides powerful database programming support. Yii Data Access Object (DAO) is built on the PHP Data Object (PDO) extension, making it...
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!