How to Count Query Results in CodeIgniter

CodeIgniter’s Query Builder class has support to get only number of results without getting all results.

Use PHP count() method

This is commonly used if we want to get both results’ data and its number of data set in results.

$this->db->select('*');
$this->db->from('posts');
$this->db->where('user_id', '10');
$query = $this->db->get();
$results = $query->result_array();
echo count($results);

Use num_rows() method

$this->db->select('count(*)');
$this->db->from('comments');
$this->db->where('user_id','2');
$query = $this->db->get();
echo $query->num_rows();

Use count_all_results() method

$this->db->select('*');
$this->db->from('posts');
$this->db->where('title LIKE', '%CodeIgniter%');
$total = $this->db->count_all_results();

Leave a Comment

Your email address will not be published. Required fields are marked *

We care about your privacy and data security. Google serves cookies to analyse traffic and show ads on this site. By using this site you agree to these cookies being set. 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