Patrick
Patrick

Reputation: 93

How to count total number of rows of table in Cakephp

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?

Upvotes: 6

Views: 18004

Answers (5)

Ma'moon Al-Akash
Ma'moon Al-Akash

Reputation: 5413

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

Upvotes: 12

Kalyan Halder
Kalyan Halder

Reputation: 1585

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.

Upvotes: 1

kamleshpal
kamleshpal

Reputation: 33

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;

Upvotes: 1

Abdou Tahiri
Abdou Tahiri

Reputation: 4408

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

Upvotes: 4

Vipul
Vipul

Reputation: 941

you also try this with condition

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

Upvotes: 7

Related Questions