codeigniter: Pagination logic to show 2 lists per

2019-06-06 06:24发布

问题:

I am having a pagination page in my controller, i am kind of puzzled in listing 2 data per page on my view. The controller code which i am using is as follows:

public function newsletter()
{
    $this->load->library('pagination');
    $config = array();

    $config["base_url"] = base_url() . "index.php/welcome/newsletter";
    $this->load->model('newsletter_model');
    $total_row = $this->newsletter_model->record_count();
    $config["total_rows"] = $total_row;
    $config["per_page"] = 2;  // per page 2 records
    $config['use_page_numbers'] = TRUE;
    $config['num_links'] = $total_row;
    $config['cur_tag_open'] = '&nbsp;<a class="current">';
    $config['cur_tag_close'] = '</a>';

    $config['page_query_string'] = FALSE;
    $config['next_link'] = 'Next';
    $config['prev_link'] = 'Previous';

    $this->pagination->initialize($config);
    if($this->uri->segment(3)){  
    $page = ($this->uri->segment(3)) ; 
    }
    else{ 
    $page = 1;
    } 
    $this->load->model('newsletter_model');
    $data["results"] = $this->newsletter_model->fetch_data($config["per_page"], $page); 
    $str_links = $this->pagination->create_links();
    $data["links"] = explode('&nbsp;',$str_links );

    $this->load->model('newsletter_model');
    $this->load->view('newsletter/newsletter',$data);
}

With the above code i am getting 2 records per page as i intended, but i could not understand the logic behind the pagination. can anyone explain me the logic worked in codeigniter pagination, with my work itself as it would be handy for me to understand it.

My Model code is as follows:

  public function fetch_data($limit, $id)
   { 

    $this->db->select('*');
    $this->db->from('ins_newsletter');
    $this->db->order_by('nl_id', 'desc');
    $this->db->limit($limit,$id);
    $query = $this->db->get();

    return $query->result_array();

}
public function record_count() 
{
    return $this->db->count_all("ins_newsletter");
}

回答1:

CI's Paginator class only generates pagination links for you.

The "record pagination" logic happens here:

$this->db->limit($limit, $offset);

$limit is the number of records to fetch, $offset is the offset of the first row to return.

To fetch the first two records, we will set $limit = 2, $offset = 0

CI translates into SQL like:

SELECT ...... FROM ins_newsletter LIMIT 0, 2;

To fetch record number 3 and 4, we will set $limit = 2, $offset = 2

CI translates into SQL like:

SELECT ...... FROM ins_newsletter LIMIT 2, 2;

Edit:

There is a small bug in your code.

The offset should be 0 for page 1, 2 for page 2, 4 for page 3, 6 for page 4, 8 for page 5...and so on.

public function fetch_data($limit, $page)
{
    $offset = ($page - 1) * $limit;
    ...
}

And I would suggest you to change the second param to $page instead of $id.