分页 CodeIgniter 4 示例

⚡ 智能摘要

分页 CodeIgniter 使用内置的分页库将大型数据库结果集拆分成易于浏览的小页面。本教程将构建一个可运行的示例,该示例查询作者表、配置每页限制并渲染编号导航链接。

  • 🗂️ 核心宗旨: 分页将大量的查询结果分成易于管理的页面,从而提高可读性并减少页面加载时间。
  • ⚙️ 库设置: 加载分页和数据库库,然后传递一个定义 base_url、total_rows 和 per_page 的 $config 数组。
  • 🔢 URI 段: uri_segment 值表示 Code点火器 URL 段包含用于跳过已显示记录的偏移量。
  • 🧱 模型层: 模型公开了 get_count() 和 get_authors($limit, $start),以便控制器只获取一个页面需要的行。
  • 🔗 导航链接: create_links() 方法会自动生成可直接设置样式的上一页链接、编号链接和下一页链接。
  • ???? 定制样式: 配置键(例如 full_tag_open 和 cur_tag_open)会将链接包装在您自己的 CSS 类或框架标记中。
  • 🤖 人工智能辅助: AI 工具可以根据表格定义搭建模型、控制器和 $config 数组,然后解释每个选项。

分页 Code点火器

数据库是鲜活的实体,会随着时间的推移而不断增长。在设计应用程序时,我们需要考虑用户需要浏览的大量记录。分页功能可以将结果拆分成易于管理的小部分。下图展示了一个分页示例。 Google 搜索。

分页 Code点火器

在本教程中,您将学习如何对数据库结果进行分页。 Code使用 Igniter 的分页库。本教程假设您已熟悉 Igniter 的基础知识。 CodeIgniter Active Record。如果您还不了解它,可以阅读之前的教程。另一个假设是您已经下载了相关软件。 Code点火器。

数据库配置

我们将从创建数据库并在其中插入一些虚拟记录开始。它将是一个包含 50 条记录的单表数据库。

运行以下脚本 MySQL 创建数据库作者表。插入 50 条虚拟记录。

CREATE SCHEMA ci_pagination;
 
DROP TABLE IF EXISTS `authors`;
 
CREATE TABLE `authors` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`first_name` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`last_name` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`email` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`birthdate` date NOT NULL,
`added` timestamp NOT NULL DEFAULT current_timestamp(),
PRIMARY KEY (`id`),
UNIQUE KEY `email` (`email`)
) ENGINE=InnoDB AUTO_INCREMENT=101 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (1, 'Brielle', 'O\'Hara', 'alexandre67@example.com', '1974-05-21', '1999-09-17 19:17:28');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (2, 'Flavio', 'Lehner', 'mafalda85@example.net', '1971-10-14', '1998-09-09 00:25:06');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (3, 'Elmira', 'Johns', 'wellington52@example.org', '1983-11-28', '2015-02-07 15:56:43');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (4, 'Elza', 'Mitchell', 'marisol46@example.org', '1989-03-08', '1992-08-21 00:21:39');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (5, 'Viva', 'Greenfelder', 'era94@example.com', '1995-04-17', '2017-04-30 05:55:39');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (6, 'Maxwell', 'VonRueden', 'mcassin@example.net', '1994-07-01', '1996-05-08 23:30:14');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (7, 'Deontae', 'Becker', 'rory.kub@example.org', '1992-02-19', '2017-07-22 11:49:15');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (8, 'Sylvester', 'Christiansen', 'erohan@example.org', '1990-09-03', '2004-05-08 08:15:37');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (9, 'Torrey', 'Strosin', 'adams.luciano@example.net', '1999-10-09', '2009-08-30 21:30:44');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (10, 'Kelli', 'Smitham', 'daniel.catalina@example.com', '2012-11-07', '1986-01-22 20:52:57');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (11, 'Abigale', 'Schuppe', 'andreanne.hayes@example.net', '2018-02-18', '1994-05-07 06:26:36');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (12, 'Letha', 'Gleason', 'eldridge.heaney@example.net', '2009-02-06', '1998-05-25 04:37:54');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (13, 'Sienna', 'Upton', 'monique57@example.org', '2017-08-17', '2009-08-08 19:08:10');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (14, 'Harley', 'Gutkowski', 'breilly@example.net', '1987-11-30', '1998-07-31 11:08:01');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (15, 'Lois', 'Bednar', 'hpouros@example.net', '2002-02-11', '2001-07-26 15:04:16');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (16, 'Gail', 'McDermott', 'reina.kerluke@example.com', '1987-03-30', '2004-12-15 20:38:29');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (17, 'Sydney', 'Strosin', 'dweber@example.net', '1985-04-29', '2010-08-07 08:50:35');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (18, 'Anne', 'Cremin', 'fritz.schmitt@example.com', '1976-02-15', '1980-03-25 05:29:41');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (19, 'Norberto', 'Bergnaum', 'franecki.javon@example.net', '1971-03-11', '1993-03-20 23:36:25');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (20, 'Arvid', 'Johns', 'pschultz@example.org', '2016-01-03', '1995-04-30 17:07:15');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (21, 'Bernita', 'Fay', 'arne96@example.org', '1983-12-26', '1987-02-23 16:55:28');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (22, 'Gonzalo', 'Gorczany', 'velma.huels@example.com', '1987-10-19', '2016-10-18 19:25:46');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (23, 'Jackie', 'Klein', 'gretchen.howe@example.com', '1971-01-20', '2010-11-16 02:58:05');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (24, 'Andrew', 'Kessler', 'collins.faye@example.org', '1984-08-07', '1971-12-15 08:46:42');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (25, 'Claire', 'Hudson', 'madalyn.wunsch@example.org', '1984-12-19', '1991-07-04 14:35:53');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (26, 'Prudence', 'Runte', 'koch.laurie@example.net', '2008-12-27', '1985-09-30 04:57:55');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (27, 'Destinee', 'Romaguera', 'tromp.tiffany@example.com', '1978-11-09', '1997-11-09 19:58:08');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (28, 'Marianna', 'Harvey', 'clovis.schuppe@example.com', '2013-08-28', '1990-08-06 19:29:19');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (29, 'Eloy', 'Lakin', 'wmorissette@example.net', '1989-12-08', '1974-03-16 03:21:16');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (30, 'Rubie', 'McClure', 'haley.louisa@example.net', '1987-09-12', '1998-07-02 10:45:36');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (31, 'Marisa', 'Stracke', 'zachary76@example.org', '1975-05-28', '1975-03-19 00:57:35');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (32, 'Jacey', 'Beatty', 'dahlia.hermann@example.org', '1979-12-17', '1971-01-21 16:50:58');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (33, 'Idella', 'Ruecker', 'elda.reichert@example.com', '2009-09-15', '1996-04-19 22:27:31');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (34, 'Dimitri', 'Bednar', 'freida.parker@example.org', '1998-12-02', '2008-12-30 23:29:57');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (35, 'Elfrieda', 'Smitham', 'padberg.rex@example.org', '2018-07-23', '1972-04-01 07:52:25');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (36, 'Dwight', 'Walter', 'gmosciski@example.org', '2016-08-15', '1994-07-02 11:06:55');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (37, 'Macie', 'Fay', 'uschuppe@example.net', '1976-01-29', '2005-12-13 18:44:46');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (38, 'Lori', 'Kshlerin', 'mhansen@example.net', '1983-04-08', '1986-01-18 16:03:52');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (39, 'Jeffry', 'Paucek', 'alisha35@example.net', '2002-10-02', '2004-03-29 07:06:03');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (40, 'Yvonne', 'Bernhard', 'jaqueline21@example.net', '2017-11-04', '1986-12-15 23:55:23');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (41, 'Ludwig', 'Heathcote', 'marcelino.kirlin@example.org', '1981-02-09', '2000-08-02 20:45:48');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (42, 'Jadyn', 'Wiegand', 'georgianna.swift@example.net', '1982-06-16', '1980-12-05 13:09:37');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (43, 'Ferne', 'Smitham', 'melany22@example.com', '1996-12-17', '1984-11-18 19:26:27');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (44, 'Meta', 'Corkery', 'xharber@example.com', '1972-03-31', '2007-01-20 00:07:31');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (45, 'Toni', 'Wolf', 'wyman.crystal@example.org', '2012-04-15', '1973-06-22 12:14:37');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (46, 'Zack', 'Luettgen', 'deion.konopelski@example.org', '2003-05-29', '2018-11-19 05:03:21');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (47, 'Kameron', 'Dietrich', 'ronaldo.torphy@example.com', '1973-05-20', '1974-09-16 20:27:17');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (48, 'Zetta', 'Lebsack', 'timmothy.vandervort@example.com', '1996-11-04', '2001-03-06 01:33:01');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (49, 'Benny', 'Hane', 'leone.lueilwitz@example.net', '2008-02-02', '2006-01-27 22:12:39');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (50, 'Evans', 'Gleason', 'ccummerata@example.org', '1999-09-09', '1990-09-26 17:50:11');

现在我们已经成功创建了数据库并插入了虚拟记录,接下来让我们配置我们的数据库。 Code使用 Igniter 应用程序与数据库通信。

打开 application/config/database.php

设置数据库连接参数类似如下

$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => 'melody',
'database' => 'ci_pagination',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);

这里,

  • 'hostname' => 'localhost',设置数据库的主机名
  • 'username' => 'root',指定数据库用户名
  • 'password' => 'melody',设置数据库密码
  • 'database' => 'ci_pagination',指定数据库名称。

我们还将在应用程序启动时自动加载数据库库。让我们来实现这一点。打开 application/config/autoload.php 文件。

按照以下代码所示加载数据库库

$autoload['libraries'] = array('database');

这就是数据库配置的全部内容。

现在让我们来研究分页的数据库模型。

CodeIgniter 分页数据库模型

在 application/models 中创建一个新模型 Authors_model

添加以下代码

<?php
 
class Authors_model extends CI_Model {
 
protected $table = 'authors';
 
public function __construct() {
parent::__construct();
}
 
public function get_count() {
return $this->db->count_all($this->table);
}
 
public function get_authors($limit, $start) {
$this->db->limit($limit, $start);
$query = $this->db->get($this->table);
 
return $query->result();
}
}

这里,

  • protected $table = 'authors'; 定义了一个受保护的变量,该变量保存模型的数据库表名。
  • public function __construct() {…} 调用父构造函数方法
  • public function get_count() {…} 返回数据库表中记录的总数。这用于分页。
  • `public function get_authors($limit, $start) {…}` 定义了一个用于从数据库中检索分页结果的方法。我们传入 `limit` 和 `start` 参数。`limit` 定义了要返回的记录总数,而 `start` 定义了要跳过的记录数。

我们的数据库模型就完成了。现在让我们创建用于响应分页结果的路由。

CodeIgniter 分页路由

打开 application/config/routes.php 中的路由文件

添加以下路线

$route['authors/(:num)'] = 'authors';

这里,

  • 我们定义了一条名为 authors 的路由,它接受一个可选的数值参数。该可选参数通过方括号定义。这条路由会调用 Authors 控制器中的 index 方法。

现在让我们继续讨论分页结果的控制器。

CodeIgniter 分页控制器

在 application/controllers 目录中创建一个新文件 Authors.php

添加以下代码

<?php defined('BASEPATH') OR exit('No direct script access allowed');
 
class Authors extends CI_Controller {
 
public function __construct() {
parent:: __construct();
 
$this->load->helper('url');
$this->load->model('authors_model');
$this->load->library("pagination");
}
 
public function index() {
$config = array();
$config["base_url"] = base_url() . "authors";
$config["total_rows"] = $this->authors_model->get_count();
$config["per_page"] = 10;
$config["uri_segment"] = 2;
 
$this->pagination->initialize($config);
 
$page = ($this->uri->segment(2)) ? $this->uri->segment(2) : 0;
 
$data["links"] = $this->pagination->create_links();
 
$data['authors'] = $this->authors_model->get_authors($config["per_page"], $page);
 
$this->load->view('authors/index', $data);
}
}

这里,

  • 类 Authors 扩展了 CI_Controller {…} 我们定义一个类 Authors 来扩展 CI_Controller 类
  • public function __construct() {…} 此方法初始化父构造函数并加载 url 助手、作者模型和分页库。
  • public function index() {…} 定义响应路线作者的方法
    • $config[“base_url”] = base_url() . “authors”; 设置分页 URL 用于生成分页链接
    • `$config[“total_rows”] = $this->authors_model->get_count();` 设置需要分页的总行数。该值通过调用 `get_count` 方法从作者模型中获取。
    • $config[“per_page”] = 10;定义每页需要显示的行数
    • $config[“uri_segment”] = 2; 指定 URL 包含用于跳过记录的值的段
    • `$this->pagination->initialize($config);` 使用我们定义的配置数组值初始化分页库。
    • `$page = ($this->uri->segment(2)) ? $this->uri->segment(2) : 0;` 检查 URI 的第二个段是否设置了跳过编号,如果未设置,则将值 0 赋给变量 `$page`。
    • $data[“links”] = $this->pagination->create_links(); 创建分页链接并将其分配给 $data 数组变量的 links 键。
    • `$data['authors'] = $this->authors_model->get_authors($config[“per_page”], $page);` 检索分页后的作者记录,并将它们赋值给 `$data` 数组变量的 `authors` 键。
    • $this->load->view('authors/index', $data); 加载作者目录中的索引视图并传入数组变量 $data。

控制器部分就完成了。现在让我们创建视图来显示数据库结果。

在 application/views 中创建新目录 authors

在 application/views/authors/index.php 中创建一个新文件 index.php

添加以下代码

<!DOCTYPE html>
<html>
<head>
<title>CodeIgniter Pagination</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https:0
</head>
<body>
<div class="container">
<h3 class="title is-3">CodeIgniter Database Pagination</h3>
<div class="column">
<table class="table is-bordered is-striped is-narrow is-hoverable is-fullwidth">
<thead>
<tr>
<th>ID</th>
<th>Contact Name</th>
<th>Contact Number</th>
<th>Email</th>
<th>City</th>
</tr>
</thead>
<tbody>
<?php foreach ($authors as $author): ?>
<tr>
<td><?= $author->id ?></td>
<td><?= $author->first_name ?></td>
<td><?= $author->last_name ?></td>
<td><?= $author->email ?></td>
<td><?= $author->birthdate ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<p><?php echo $links; ?></p>
</div>
</div>
</body>
</html>

这里,

  • 遍历 $authors 变量的结果,并将结果打印到表格中。
  • 在表格底部打印分页链接。

现在让我们开始申请,看看结果如何。

在本教程中,我们使用内置的 PHP Web 服务器,但您可以使用任何支持 PHP.

打开终端

运行以下命令

cd C:\Sites\ci-app
php -S localhost:3000

这里,

  • 上述命令浏览到应用程序代码目录并在端口 3000 上启动内置服务器。

注意:应用程序路径必须与您下载的路径一致。 CodeIgniter。您可以使用计算机上任何空闲的端口号。不必使用端口 3000。

打开网页浏览器并加载以下内容 URL

http://localhost:3000/authors

您应该能够获得类似以下的结果

CodeIgniter 分页控制器

如何定制 CodeIgniter 分页链接

默认情况下,`create_links()` 方法输出的是普通的锚点标签。您可以将这些链接包装在您自己的标记中,使其与 CSS 框架(例如 `<link>`)相匹配。 Bootstrap 或者使用 Bulma。在调用 initialize() 之前,将样式键添加到同一个 $config 数组中。

$config['full_tag_open'] = '<nav><ul class="pagination">';
$config['full_tag_close'] = '</ul></nav>';
$config['num_tag_open'] = '<li class="page-item">';
$config['num_tag_close'] = '</li>';
$config['cur_tag_open'] = '<li class="page-item active"><a class="page-link">';
$config['cur_tag_close'] = '</a></li>';
$config['next_link'] = 'Next &raquo;';
$config['prev_link'] = '&laquo; Previous';

下面介绍最常用的配置键。

  • full_tag_open / full_tag_close: 用于包裹所有链接的标记,非常适合用于或者容器。
  • 标签打开数/标签关闭数: 每个编号页面链接周围的标记。
  • cur_tag_open / cur_tag_close: 在当前活动页码周围添加标记。
  • 下一个链接 / 上一个链接: 用于“上一页”和“下一页”按钮的文本或符号。

由于样式完全存在于配置中,因此您可以通过编辑单个数组来重新设置整个应用程序的分页样式,而无需触及控制器逻辑。

常见问题

per_page 值设置每页显示的记录数,而 uri_segment 值则指示 uri_segment 的值。 Code点火器 URL 段包含偏移量编号。它们共同控制显示的行数和加载的页面。

通常情况下,uri_segment 值与您的偏移量位置不匹配。 URL计算域名后的段数,并将 uri_segment 设置为该数字,以便 create_links() 读取正确的页面偏移量。

是的。分页只需要总行数和每页行数。您可以手动提供总行数,然后自行对每页数据进行切片,从而对数组、API 结果或文件进行分页。

是的。给定表名和列名,AI 可以生成模型、$config 数组和控制器 index() 方法。 Rev查看 base_url 和 uri_segment 的值,然后测试生成的链接。

是的。粘贴你的控制器和 URL 结构,人工智能可以发现不匹配的 uri_segment 值、缺少 base_url 斜杠或不正确的 total_rows 来源,然后建议尝试正确的配置。

总结一下这篇文章: