I\'m using a complex SQL query in a Codeigniter model with a limit applied. I\'d like to count the total number of rows that would have been found if the limit and offset had no
One way I can think is to have variable $count when you call your function, and it will go something like this:
function your_function($count = FALSE) {
$this->db->select(...)
//before limit you do this:
if($count != FALSE):
return $this->db->get->result_array()
else :
return $this->db->limit($limit, $offset)->get()->result_array();
endif;
}
This way you can call function two time - one for count and the other for limit query:
$count = count($this->your_function(TRUE));
$data['query] = $this->your_function();
I've previously had the exact same requirement for pagination, and I was able to make it work using CodeIgniter Active Record.
First, set the option SQL_CALC_FOUND_ROWS
as a pseudo column in your select statement and set escape query to false:
$this->db->select('SQL_CALC_FOUND_ROWS null as rows, other columns ...',FALSE);
Then, after you execute your query with the limit and offset in place assign the result set to a return array:
$data = $this->db->get();
$return['results'] = $data->result();
// Do something with the results
Finally, run a second query to get the found rows and also assign that to the return array. I'm using method chaining here to do it all in one step.
$return['rows'] = $this->db->query('SELECT FOUND_ROWS() count;')->row()->count;
And return the result and row count array.
return $return;