This article 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 also you learn Also Read:Count Query Codeigniter Tutorial. Or to know if your mysql DB query actually returns any records at all. While you can count it using select mysql DB query, there are better ways to fetching the job done in codeingniter.
codeigniter count rows
CodeIgniter Count Query Results & Number of Rows in Table
Active Records library provides some handy functions to count the mysql DB query resultset or get row count in a table. We’ll see what those functions are and how to use them here.
Sample MySQL Table:
Count Query Results in CodeIgniter:
There are two best ways to count mysql DB query results in php codeigniter. The first one is using the num_rows() function.
1. Function: num_rows()
This function counts the number of rows returned by a mysql DB query. You have to use it like this,
Sometimes you may wonder if your database mysql DB 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)
2. Function: count_all_results()
The count_all_results() function is another way to determine the number of rows returned by a particular Active Record mysql DB query. This works with all sorts of conditional queries using where, like clauses.
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 database table name to the function to fetching the row count such as this,