CodeIgniter 3 分页必须加载 library 而非 helper:$this->load->library('pagination'),并确保已加载 url 辅助函数;配置中 base_url 需完整路径,uri_segment 和 per_page 必须与 URL 结构及数据库 limit 一致;total_rows 必须手动通过 count_all_results() 设置,否则 create_links() 返回空。

CodeIgniter 3 的 pagination 辅助函数怎么初始化才不报错
直接用 $this->load->library('pagination'),不是 helper。这是最常踩的坑:名字叫“pagination helper”,但实际是 library,不是 helper。官方文档里也写得模糊,很多人搜“pagination helper”就去 load_helper('pagination'),结果报 Call to undefined function pagination_create() 这类错误。
正确做法是:
- 确保已加载
url辅助函数($this->load->helper('url')),否则生成的链接会出问题 - 必须用
$this->load->library('pagination'),且推荐传配置数组,别依赖默认值 - 配置里
base_url必须带完整路径(含index.php或重写后的 clean URL),比如http://example.com/news/page/,不能只写/news/page/
分页链接生成失败或跳转后数据没变,怎么查 per_page 和 uri_segment
分页失效,90% 是这两个参数没对上:当前页码从 URL 哪一段读?每页取几条?
uri_segment 指的是 URL 中表示页码的段数。比如 URL 是 http://example.com/news/page/3,那页码在第 4 段(从 1 开始数),uri_segment 就该设为 4;如果是 http://example.com/news/3,就是 3。设错了,$this->pagination->create_links() 仍能输出 HTML,但 $this->uri->segment(4) 读不到值,导致永远查第一页。
per_page 要和你查数据库时用的 limit() 一致。CI 不自动帮你做 limit,你得自己算偏移量:$offset = ($this->uri->segment(4)) ? $this->uri->segment(4) : 0;,再传给 $this->db->limit(10, $offset)。
为什么 $this->pagination->create_links() 返回空字符串
返回空,不是代码写错了,而是没满足「有总记录数」+「总页数 > 1」这两个前提。
CI 分页库不会主动查总数,你必须手动调用 $this->db->count_all_results()(注意:要复用相同查询条件,别漏 where),然后把结果赋给 total_rows 配置项。漏了这步,total_rows 默认是 0,num_links 算出来是 0,create_links() 就啥也不输出。
常见错误写法:
$query = $this->db->get('posts'); // 没加 where,但 count_all_results() 前又没重置条件
$this->db->count_all_results(); // 查的是全表,不是过滤后结果
正确顺序:
- 先构建查询(含
where、like等) - 调用
$this->db->count_all_results()得到total_rows - 再执行
$this->db->get()取当前页数据 - 最后把
total_rows塞进分页配置
自定义分页样式时,full_tag_open 和 next_link 怎么避免破坏语义
直接改 full_tag_open 里塞 <div class="pagination"> 很常见,但容易忽略两个点:一是 next_link / prev_link 默认值是纯文本(如 >),不带 <a> 标签,你得手动包一层;二是如果当前是第一页,prev_link 默认显示为空字符串,但如果你设了 prev_link 为 '<a href="#"><<>,它就真会渲染出来,变成死链。</<>
稳妥做法:
- 用
first_tag_open/last_tag_open控制首尾,别全靠full_tag_open - 把
next_link设为空(''),改用next_tag_open+next_tag_close控制容器 - 如果要禁用首页/末页按钮,别删配置项,设
first_link为false,否则可能触发 Notice
分页不是配完就能跑通的模块,核心是三处对齐:URL 段位、数据库 offset、总数统计逻辑。少对上一个,页面就静默失败。









