我正在制作一个 Codeigniter 3 应用程序,其中包含一个已分页的表格(大约有 100 行),每页 10 行。
在家庭 Controller 中我有:
public function index() {
$this->load->model('Customer');
$this->load->library('pagination');
$config = [
'base_url' => base_url("index.php"),
'per_page' => 10,
'total_rows' => $this->Customer->get_num_rows(),
'uri_segment' => 3,
'first_tag_open' => '<li>',
'first_tag_close' => '</li>',
'last_tag_open' => '<li>',
'last_tag_close' => '</li>',
'full_tag_open' => '<ul class="pagination">',
'full_tag_close' => '</ul>',
'next_tag_open' => '<li>',
'next_tag_close' => '</li>',
'prev_tag_open' => '<li>',
'prev_tag_close' => '</li>',
'num_tag_open' => '<li>',
'num_tag_close' => '</li>',
'cur_tag_open' => '<li class="active"><a>',
'cur_tag_close' => '</a></li>',
];
$this->pagination->initialize($config);
$customers = $this->Customer->getCustomers($config['per_page'], $this->input->get('page'));
$this->load->view('home', ['records'=>$customers]);
}
在模型文件中我有:
class Customer extends CI_Model {
public function __construct() {
$this->load->database();
}
public function getCustomers($limit, $offset) {
$this->db->limit($limit, $offset);
$query = $this->db->get('customers');
return $query->result();
}
}
View :
<div class="pagination-container text-center">
<?php echo $this->pagination->create_links(); ?>
</div>
最佳答案
使用您当前的模型方法
public function getCustomers($limit, $offset) {
$this->db->limit($limit, $offset);
$query = $this->db->get('customers');
return $query->result();
}
您正在传递 $limit,您将其传递为 10。 您的 $offset 似乎是您所看到的结果所示的页码。
例如,如果您的 uri 段值为 2(第 2 页),则您实际上将方法中的限制设置为
$this->db->limit(10, 2);
将显示记录 3 到 13。
您可以通过使用以下 var_dump 语句作为调试代码来检查值来验证这一点。
public function getCustomers($limit, $offset) {
$this->db->limit($limit, $offset);
var_dump($limit, $offset);
$query = $this->db->get('customers');
return $query->result();
}
如果您无法直接在页面上看到这些内容,则当您在网络浏览器中对 HTML 执行查看源代码时,您会找到这些内容的输出。
所以你需要做的是设置$offset来反射(reflect)条目数*页码。
因此,第 1 页将是 $offset = $limit * ($page - 1) = 10 * 0 = 0
的记录,限制为 10记录 1 至 10。
第 2 页 应该是带有 $offset = $limit * ($page - 1) = 10 * 1 = 10
的记录,将给出记录 11-20
因此这导致您需要将方法参数中的 $offset 重命名为 $page 并计算所需的 $offset
public function getCustomers($limit, $page) {
$offset = 0;
if($page > 0) {
$offset = $limit * ($page - 1);
}
$this->db->limit($limit, $offset);
$query = $this->db->get('customers');
return $query->result();
}
希望这会有所帮助。
关于php - Codeigniter 3 分页错误 : the second page shows records 3 to 13 instead of 11 to 20,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45742230/