Count Query Results in CodeIgniter

CodeIgniter’s Query Builder class is a handy tool for working with databases. One of its most useful features is the ability to get only the number of results without getting all results. This can be very helpful when working with large data sets. For example, if you only need to know the total number of rows in a table, you can use the Query Builder’s methods to get just that. This can save you a lot of time and resources, as you don’t need to fetch all the data just to get the count.

Here are 3 ways you can use to count the returned results of a query:

$this->db->select('*');
$this->db->from('articles');
$this->db->where('author_id', '3');
$query = $this->db->get();
$results = $query->result_array();
echo count($results);
$this->db->select('count(*)');
$this->db->from('students');
$this->db->where('class_id', '7');
$query = $this->db->get();
echo $query->num_rows();
$this->db->select('*');
$this->db->from('comments');
$this->db->where('comment LIKE', '%developers%');
$counter = $this->db->count_all_results();

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close