CakePHP Count Records

How to count a record in tables? For example, you have users table that contain numbers of users with different gender. Developer can count 1) total registered users; 2) Male users; and 3) Female users. The method is to create a find function and make it count the numbers of record. 

To count all records in users table, developer need to identify where the result should be display. Let assume that the result for total numbers of user will be display at index page. So developer need to add these code to the controller (UsersController.php) inside the public function index as shown below:

$this->set('all_user', $this->User->find('count'));

Sample view in public function index:

public function index() {
	$this->set('all_user', $this->User->find('count'));
	$this->User->recursive = 0;
	$this->set('users', $this->paginate());

Next, in the index.ctp page at, add the following code to print the count result as shown below:

Total Users: <?php echo $all_user; ?>

If you have a conditional count for example, total users based on gender. The find count method need to have a conditional measure as shown below:

//Count Male User
$this->set('user_male', $this->User->find('count', array(
	'conditions' => array(
			'User.gender' => 'Male')
//Count Female User
$this->set('user_female', $this->User->find('count', array(
	'conditions' => array(
			'User.gender' => 'Female')

In the index.ctp it should be call as shown below:

Total Users: <?php echo $all_user; ?><br>
Total Male Users: <?php echo $user_male; ?><br>
Total Female Users: <?php echo $user_female; ?>

If there is another count criteria for example role and status, developer can combine the condition as shown below:

$this->set('user_administrator_active', $this->User->find('count', array(
	'conditions' => array(
			'User.role' => 'Administrator',
			'User.gender' => 'Male',
			'User.status' => 'Active')

and the count result should be call as:

<?php echo $user_administrator_active; ?>

That all :) Hopefully it is useful for your project and application development :)