How to count the total number of rows of table and pass it to the variable? For example, I have product table and there are 10 products in it. I want to count all the rows and get the result 10 and pass it to the variable $rowcount. How can I do it?
Asked
Active
Viewed 1.8k times
5 Answers
12
use find('count')
For example:
$total = $this->Article->find('count');
If you want to use a condition in your query, then pass the conditions array, here is a sample code:
$pending = $this->Article->find('count', array('conditions' => array('Article.status' => 'pending')));

Ma'moon Al-Akash
- 4,445
- 1
- 20
- 16
-
what about with conditions? – Wayne Tun Jul 02 '14 at 18:32
7
you also try this with condition
$rowcount = $this->Product->find('count', array('conditions' => array('Product.fieldName' => 'value')

Vipul
- 896
- 7
- 14
4
u can do it with find('count') method
$this->set('rowcount',$this->Product->find('count'));
or simply use count() function if had already the products in a variable $products to avoid another Mysql query
$this->set('rowcount',count($products));

Abdou Tahiri
- 4,338
- 5
- 25
- 38
1
By Using this you can count data with passing conditions in where
$assignment = TableRegistry::get('Assignment');
$query = $assignment->find();
$query->select(['count' => $query->func()->count('id')]);
$query->where(['Assignment.user_id'=>$user_id]);
$assignment = $query->toArray();
$assignment_count = $assignment[0]->count;
return $assignment_count;

kamleshpal
- 33
- 8
1
In CakePHP 3.x you can query like this:
$count = $this->Students->find()->count();
Or
TableRegistry::get('Students')->find()->count();
Here student is example model. Replace with your model name. Thanks.

Kalyan Halder
- 1,485
- 24
- 28