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

Can yii execute sql?

爱喝马黛茶的安东尼
爱喝马黛茶的安东尼Original
2019-12-09 10:42:341840browse

Can yii execute sql?

1. Create CDbCommand command object

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

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();

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();

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

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!

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