Home > PHP Framework > YII > Can yii execute sql?

Can yii execute sql?

爱喝马黛茶的安东尼
Release: 2019-12-09 10:42:34
Original
1892 people have browsed it

Can yii execute sql?

1. Create CDbCommand command object

$sql = "select * from users where id=1";
$connection=Yii::app()->db;
$command=$connection->createCommand($sql);
Copy after login

2. Execution of SQL statement

The CDbCommand object has two (kinds) methods to execute SQL statements.

2.1 execute() method

is used for data update (non-query) operations (INSERT, UPDATE and DELETE), and returns the number of record rows affected by the operation. .

$rowCount=$command->execute();
Copy after login

2.2 query() and queryXXX() methods

are used for queries, corresponding to the SELECT statement.

2.2.1 query() method

$dataReader=$command->query();
返回CDbDataReader对象,注意这代表结果集而不是记录,可以通过以下方法来获取(遍历)记录:
// CDbDataReader::read()可以一次获取一行数据,到末尾时返回false
while(($row=$dataReader->read())!==false) 
// CDbDataReader实现了迭代器接口因此可以使用foreach遍历
foreach($dataReader as $row)
// 一次性返回所有的记录(数组)
$rows=$dataReader->readAll();
Copy after login

2.2.2 Derived queryXXX() method

#返回所有结果记录数组
$rows=$command->queryAll();
#返回第一行记录
$row=$command->queryRow();      // query and return the first row of result
#返回所有记录的第一列
$column=$command->queryColumn(); // query and return the first column of result
#返回第一行记录的第一列
$value=$command->queryScalar();  // query and return the first field in the first row
Copy after login

PHP Chinese There are a lot of free Yii introductory tutorials on the Internet, everyone is welcome to learn!

The above is the detailed content of Can yii execute sql?. For more information, please follow other related articles on the PHP Chinese website!

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