To paginate, you need to read a set of records twice:
- As soon as you read the whole set, so that it can count the general records of numbers
- Then, to read the record window to display
Here is an example that I used for the project. In the table "banner" there is a list of banners that I want to show on a paginated page:
- Using the public class property to store shared records (public $ total_records)
- Using a private function to build a query (which is common to both activities). The ($ isCount) parameter that we pass to this function reduces the amount of data that the query generates, because we only need one field to count the rows, but when we read the data window, we need all the required fields.
- The get_list () function first calls the database to find the total and stores it in $ total_records, and then reads the data window to return to the caller.
- Remember that we cannot access $ total_records without first calling the get_list () method!
class Banner_model extends CI_Model { public $total_records; //holds total records for get_list() public function get_list($count = 10, $start = 0) { $this->build_query(); $query = $this->db->get(); $result = $query->result(); $this->total_records = count($result); //store the count $this->build_query(); $this->db->limit($count, $start); $query = $this->db->get(); $result = $query->result(); return $result; } private function build_query($isCount = FALSE) { $this->db->select('*, b.id as banner_id, b.status as banner_status'); if ($isCount) { $this->db->select('b.id'); } $this->db->from('banner b'); $this->db->join('company c', 'c.id = b.company_id'); $this->db->order_by("b.id", "desc"); //latest ones first }
And now from the controller we call:
$data['banner_list'] = $this->banner_model->get_list(); $config['total_rows'] = $this->banner_model->total_records;
Everything becomes more complicated when you start using JOINs, for example, in my example, where you want to show banners from a certain company! You can read my blog post on this subject further:
http://www.azmeer.info/pagination-hitting-the-database-twise/
source share