CodeIgniter Count Query Results & Number of Rows in Table

On 8/04/2016

This tutorial will show you how to count query results and number of rows in table in codeigniter. At times you may be interested in knowing the number of rows in a table rather than fetching the records itself. Or to know if your sql query actually returns any records at all. While you can count it using select query, there are better ways to get the job done in codeingniter.

Active Records library provides some handy functions to count the query resultset or get row count in a table. We'll see what those functions are and how to use them here.

Sample Table:

codeigniter-count-query-results-number-of-rows-in-table
Table - Employees

Count Query Results in CodeIgniter:

There are two ways to count query results in codeigniter. The first one is using the num_rows() method.

1. Function: num_rows()

This function counts the number of rows returned by a sql query. You have to use it like this,

$this->db->where('EmpID >=', 5);
$query = $this->db->get('Employees');
echo $query->num_rows();

// Outputs, 4

Sometimes you may wonder if your database query actually returns any results at all. In such case you can first check if the result set is empty or not.

if ($query->num_rows() > 0)
{
   foreach ($query->result() as $row)
   {
      echo $row->EmpID;
      echo $row->EmpName;
      echo $row->Designation;
   }
}

2. Function: count_all_results()

The count_all_results() method is another way to determine the number of rows returned by a particular Active Record query. This works with all sorts of conditional queries using where, like clauses.

$this->db->select('*');
$this->db->from('Employees');
$this->db->like('Designation', 'Manager');
echo $this->db->count_all_results();

// Outputs, 2

If you simply want to get the row count of a table rather than of a query, just pass the table name as parameter to count_all_results() function.

echo $this->db->count_all_results('Employees');

// Outputs, 8

CodeIgniter - Count Number of Rows in Table:

If you want to count just the number of rows in a database table you can use the function $this->db->count_all(). Just pass the table name to the method to get the row count like this,

echo $this->db->count_all('Employees');

// Outputs, 8
Read Also:

Using the above discussed active record functions one can easily get row count of a table & count query result in codeigniter.

No comments:

Post a Comment

Contact Form

Name

Email *

Message *