我仍然对codeigniter分页感到困惑。我制作如下模型和控制器文件:
我的模特:
function getAllBooks($limit, $offset)
{
$query = $this->db->query("SELECT * FROM books as b LEFT JOIN publishers as p ON b.publishers_id=p.publishers_id LEFT JOIN categories as c ON b.cat_id=c.cat_id ORDER BY books_id DESC LIMIT $limit, $offset");
return $query;
}
function getCount($table)
{
$query = $this->db->query("SELECT * FROM $table");
return $query;
}
我的控制器
public function page()
{
$offset = '';
if($this->uri->segment(3) == FALSE){
$offset = 0;
}else{
$offset = $this->uri->segment(3);
}
$limit = 3;
$data['books'] = $this->model_front->getAllBooks($limit, $offset);
$all_pages = $this->model_front->getCount('books');
$config['base_url'] = base_url() . 'catalog/page/';
$config['total_rows'] = $all_pages->num_rows();
$config['per_page'] = $limit;
$config['uri_segment'] = 3;
$config['use_page_numbers'] = TRUE;
...
$this->pagination->initialize($config);
....
}
代码成功运行。但让我感到困惑的是这个计划正在发生:
Item 1 | Item 2 | Item 3 | // for main view
当我点击下一个按钮时,结果是这样的,依此类推:
Item 3 | Item 4 | Item 5 | // Second page
Item 4 | Item 5 | Item 6 | // Third page
Item 5 | Item 6 | Item 7 | // Fourth page
仅供参考,我有10条测试记录,我希望每页显示3条记录。 我仍然困惑如何在每页显示3条记录:
Item 1 | Item 2 | Item 3 | // Main view
Item 4 | Item 5 | Item 6 | // Second page
Item 7 | Item 8 | Item 9 | // Third page
Item 10 | empty | empty | // Last page
请指教。我希望你理解我的问题的意图。
提前致谢
答案 0 :(得分:0)
您只是与$offset
和$limit
混淆了。第一个参数指定要返回的第一行的偏移量,第二个参数指定要返回的最大行数。
在$offset = ($this->uri->segment(3)-1) * $limit)
部分中使用此代码else
,然后在if语句之前向上移动变量$limit = 3;
。
//Your code
$offset = '';
$limit = 3;
if($this->uri->segment(3) == FALSE){
$offset = 0;
}else{
$offset = ($this->uri->segment(3)-1) * $limit);
}
//Your code
使用此查询:
SELECT * FROM books as b LEFT JOIN publishers as p ON b.publishers_id=p.publishers_id LEFT JOIN categories as c ON b.cat_id=c.cat_id ORDER BY books_id DESC LIMIT $offset,$limit
OR
SELECT * FROM books as b LEFT JOIN publishers as p ON b.publishers_id=p.publishers_id LEFT JOIN categories as c ON b.cat_id=c.cat_id ORDER BY books_id DESC LIMIT $limit OFFSET $offset;
而不是
SELECT * FROM books as b LEFT JOIN publishers as p ON b.publishers_id=p.publishers_id LEFT JOIN categories as c ON b.cat_id=c.cat_id ORDER BY books_id DESC LIMIT $limit, $offset