Codeigniter pagination offset issue

时间:2017-06-15 10:36:05

标签: codeigniter pagination

My view:

 <?php echo $this->pagination->create_links();?>

My controller:

public function __construct()
{
    parent:: __construct();
    $this->load->model('admin_products_model');
    $this->load->library('pagination');
}

function index()
{   
    $config['base_url'] = base_url().'products/index/';
    $config['total_rows']=$this->db->get('products')->num_rows();
    $config['per_page']=10;
    $config['num_links']=10;
    $config['use_page_numbers'] = TRUE;

    $this->pagination->initialize($config);

    $page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
    $data['products']= $this->admin_products_model->getProducts($config['per_page'],$page); 

    $this->load->view('products',$data);
}

My model:

function getProducts($limit,$offset)
{
    $this->db->limit($limit);
    $this->db->offset($offset);
    $query = $this->db->get('products');

    if($query->num_rows()>0)
    {
        foreach($query->result() as $row){
            $products[]=$row;       
        }
        return $products;
    }
}

As a result, when I click on the navigation links, the results ID's aren't ascending by groups of 10. For example 1st page: 85-95. 2nd page: 86-96. etc. instead of 85-95, 96-106.

1 个答案:

答案 0 :(得分:1)

控制器功能:

public function index()
{
    $config ['base_url'] = base_url().'products/index/';
    $config ['total_rows'] = $this->db->get('product')->num_rows();
    $config ['uri_segment'] = 3;
    $config ['per_page'] = 10;
    $config ['num_links'] = 10;

    $this->pagination->initialize($config);

    $page = $config ['per_page']; // how many number of records on page
    $segment = $this->uri->segment ( 3 ); // from which index I have to count $page number of records

    $data['products']= $this->products_model->getProducts($page, $segment); 

    $this->load->view('products', $data);
}

模型功能

public function getProducts($page, $segment)
{
    $this->db->select("prid");
    $this->db->limit($page, $segment);
    $query = $this->db->get('product');

    return $query->result();        
}

查看:

<?php
echo "<pre>";
print_r($products);
echo "</pre>";
?>
<br>
<br>
<?php echo $this->pagination->create_links();?>

您错过了代码中的$page$offset内容。您不必在模型中单独传递它们,在$this->db->limit($page, $offset);

中提及它们