php - 管理 Codeigniter 分页

标签 php mysql codeigniter pagination

我仍然对 codeigniter 分页感到困惑。我制作模型和 Controller 文件如下:

我的模型:

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;
}

我的 Controller

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

请给我建议。希望您能理解我问题的意图。

提前致谢

最佳答案

您只是混淆了 $offset$limit。第一个参数指定要返回的第一行的偏移量,第二个参数指定要返回的最大行数。

else部分使用这段代码$offset = ($this->uri->segment(3)-1) * $limit),然后向上移动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

或者

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

关于php - 管理 Codeigniter 分页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23669652/

相关文章:

php - array_intersect_key PHP 数组与 MYSQL 数据库

codeigniter - 如何在Codeigniter中验证数组值

php - 使用带有多个包含的 php 读取和写入数据库

mysql - 使用外部键引用插入到选择中

php - 如何从多个表中获取结果

php - 在 CodeIgniter 中绕过 Controller 的方法?

jquery - 数据表分页搜索框不起作用

php - 如何在if else语句中调出mysql的结果

php - mysqli - php - 返回多个表的所有结果

JavaScript - 如何从下拉选择中执行特定查询?