Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii Framework: How to get the num_rows?

Tags:

yii

As the official documentation does not say how to do a simply "num_rows" with their system, i need some help here: How to get the amount of rows in the result set ?

like image 675
Sliq Avatar asked Oct 18 '12 17:10

Sliq


2 Answers

Assuming:

$connection=Yii::app()->db;
$command=$connection->createCommand($sql);

This will work for insert, update and delete:

$rowCount=$command->execute();

execute(): performs a non-query SQL statement, such as INSERT, UPDATE and DELETE. If successful, it returns the number of rows that are affected by the execution.

For select, you could do the following:

$dataReader=$command->query();

This generates the CDbDataReader instance and CDbDataReader provides a rowCount property

http://www.yiiframework.com/doc/api/1.1/CDbDataReader#rowCount-detail

$rowCount = $dataReader->rowCount;

About rowCount => Returns the number of rows in the result set. Note, most DBMS may not give a meaningful count. In this case, use "SELECT COUNT(*) FROM tableName" to obtain the number of rows.

like image 180
ews2001 Avatar answered Nov 17 '22 09:11

ews2001


ActiveRecord has count method which can be used.

$cntCriteria = new CDbCriteria();
$cntCriteria->condition = "categoryId = :categoryId";
$cntCriteria->params[':categoryId'] = $categoryRow->categoryId;
$articleCount = Article::model()->count($cntCriteria);
like image 5
Jaydeep Rajput Avatar answered Nov 17 '22 11:11

Jaydeep Rajput