search
HomeBackend DevelopmentPHP TutorialYii learning summary data access object (DAO), yiidao_PHP tutorial

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...
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
What is the full form of PHP?What is the full form of PHP?Apr 28, 2025 pm 04:58 PM

The article discusses PHP, detailing its full form, main uses in web development, comparison with Python and Java, and its ease of learning for beginners.

How does PHP handle form data?How does PHP handle form data?Apr 28, 2025 pm 04:57 PM

PHP handles form data using $\_POST and $\_GET superglobals, with security ensured through validation, sanitization, and secure database interactions.

What is the difference between PHP and ASP.NET?What is the difference between PHP and ASP.NET?Apr 28, 2025 pm 04:56 PM

The article compares PHP and ASP.NET, focusing on their suitability for large-scale web applications, performance differences, and security features. Both are viable for large projects, but PHP is open-source and platform-independent, while ASP.NET,

Is PHP a case-sensitive language?Is PHP a case-sensitive language?Apr 28, 2025 pm 04:55 PM

PHP's case sensitivity varies: functions are insensitive, while variables and classes are sensitive. Best practices include consistent naming and using case-insensitive functions for comparisons.

How do you redirect a page in PHP?How do you redirect a page in PHP?Apr 28, 2025 pm 04:54 PM

The article discusses various methods for page redirection in PHP, focusing on the header() function and addressing common issues like "headers already sent" errors.

Explain type hinting in PHPExplain type hinting in PHPApr 28, 2025 pm 04:52 PM

Article discusses type hinting in PHP, a feature for specifying expected data types in functions. Main issue is improving code quality and readability through type enforcement.

What is PDO in PHP?What is PDO in PHP?Apr 28, 2025 pm 04:51 PM

The article discusses PHP Data Objects (PDO), an extension for database access in PHP. It highlights PDO's role in enhancing security through prepared statements and its benefits over MySQLi, including database abstraction and better error handling.

How to create API in PHP?How to create API in PHP?Apr 28, 2025 pm 04:50 PM

Article discusses creating and securing PHP APIs, detailing steps from endpoint definition to performance optimization using frameworks like Laravel and best security practices.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!