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
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;