How to count total number of rows of table in Cakephp

16,819

Solution 1

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

Solution 2

you also try this with condition

$rowcount = $this->Product->find('count', array('conditions' => array('Product.fieldName' => 'value')

Solution 3

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

Solution 4

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;

Solution 5

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.

Share:
16,819

Related videos on Youtube

Patrick
Author by

Patrick

Updated on September 24, 2022

Comments

  • Patrick
    Patrick about 1 year

    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?

  • Wayne Tun
    Wayne Tun over 9 years
    what about with conditions?