count number of records

I want to display total number of books per user

here is my admin controller

public function actionAdmin()



	$criteria=new CDbCriteria;

	$pages=new CPagination(Books::model()->count($criteria));



	$sort=new CSort('Books');










try this

do you have any example?


if (Books::model()->count("is_active = 1") != 0) {

	// do somethimg if count of active books not equals 0


else {

	// echo "You haven't any books";


Thanks. working

Count is working but it count all records. I want

if ($model->User_id == Yii::app()->user->id) then will count his books. can you tell me how

Here is my view code

<?php foreach($models as $n=>$model): ?>

&lt;?php if (&#036;model-&gt;User_id == Yii::app()-&gt;user-&gt;id){ ?&gt;

&lt;tr class=&quot;&lt;?php echo &#036;n%2?'even':'odd';?&gt;&quot;&gt;

&lt;td&gt;&lt;?php echo CHtml::encode(&#036;model-&gt;id); ?&gt;&lt;/td&gt;

&lt;td&gt;&lt;?php echo CHtml::encode(&#036;model-&gt;name); ?&gt;&lt;/td&gt;


if (TN::model()-&gt;count(&quot;Book_id = 1&quot;) &#33;= 0) { ?&gt;

    &lt;td&gt;&lt;?php echo CHtml::link(Book::model()-&gt;count(&quot;Book_id&quot;), array('test','id'=&gt;&#036;model-&gt;id), array('target'=&gt;'_blank')); ?&gt;&lt;/td&gt;



else { ?&gt;

    &lt;td&gt;&lt;?php echo &quot;No Books&quot;; ?&gt;&lt;/td&gt;

&lt;?php } ?&gt;	

&lt;td&gt;&lt;?php echo CHtml::encode(&#036;model-&gt;Notes); ?&gt;&lt;/td&gt;


<?php } ?>

<?php endforeach; ?>

can you tell me what would you like to do??

count is very simple.


SELECT COUNT(*) FROM books WHERE user_id = 1;


is the same as

Books::model()->count("`user_id` = 1");

if you want to print table with user_id, user_name, and books_count, you should use a join, because counting books for every row is not very effective …

My point is if ($model->User_id == Yii::app()->user->id) then count the book and print books number. I know the sql command and it count the books. but problem is when I use in yii then count all books.

Yes I want to print user_id, user_name and books_count.

Actually I want to count number of field records (books) where $model->User_id == Yii::app()->user->id). and view the total number of books