Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between $query>num_rows() and $this->db->count_all_results() in CodeIgniter & which one is recommended

In a scenario I need to know the count of recordset a query will return, which in codeigniter can be done by $query->num_rows() or $this->db->count_all_results(). Which one is better and what is the difference between these two?

like image 695
Kumar Avatar asked Aug 12 '11 07:08

Kumar


2 Answers

With num_rows() you first perform the query, and then you can check how many rows you got. count_all_results() on the other hand only gives you the number of rows your query would produce, but doesn't give you the actual resultset.

// num rows example $this->db->select('*'); $this->db->where('whatever'); $query = $this->db->get('table'); $num = $query->num_rows(); // here you can do something with $query  // count all example $this->db->where('whatever'); $num = $this->db->count_all_results('table'); // here you only have $num, no $query 
like image 107
danneth Avatar answered Oct 06 '22 03:10

danneth


$this->db->count_all_results is part of an Active Record query (preparing the query, to only return the number, not the actual results).

$query->num_rows() is performed on a resultset object (after returning results from the DB).

like image 41
Jens Roland Avatar answered Oct 06 '22 05:10

Jens Roland