Codeigniter Active Record - Count Total Found Rows with Limit (MySQL)

前端 未结 2 568
谎友^
谎友^ 2021-02-10 16:20

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

2条回答
  •  生来不讨喜
    2021-02-10 17:19

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

提交回复
热议问题