PHP的CI框架之分页
这里使用的示例是以分页的方式显示国家名称,数据库文件
对于分页,需要知道两个数据: 1、数据的总条目数 2、每页显示的条目数
Model
初始化
public function __construct()
{
parent::__construct();
// 下面的代码将根据你的 数据库配置 加载并初始化数据库类
$this->load->database();
}
查询总条目数
public function country_count()
{
return $this->db->count_all("countries");
}
查询特定条目数,$limit表示查询的条目数,$start就是offset
public function fetch_countries($limit, $start) {
$this->db->limit($limit, $start);
$query = $this->db->get("countries");
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$data[] = $row;
}
return $data;
}
return false;
}
Controller
初始化
public function __construct() {
parent:: __construct();
$this->load->helper("url");
$this->load->model("countries");
$this->load->library("pagination");
}
构建方法
public function countries()
{
// 这四个参数是必需的
$config['base_url'] = base_url() . 'demo/countries/';
$config['total_rows'] = $this->countries->country_count();
$config['per_page'] = 6;
$config["uri_segment"] = 3;//自动检测你 URI 的哪一段包含页数
//-------------------------
$this->pagination->initialize($config);
//三元运算,$this->uri->segment(3)非空就执行$this->uri->segment(3)否则赋值为0
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
$result['results'] = $this->countries->fetch_countries($config['per_page'],$page);
$result["links"] = $this->pagination->create_links();
$this->load->view("example1", $result);
}
其中$this->uri->segment(3)是获取URL中第三段的内容,例如:
class Hello extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper('url');
}
public function test()
{
$result = $this->uri->segment(2);
var_dump($result);
}
}
在浏览器中运行示例 http://localhost/index.php/hello/test/ 结果

改变 segment()中的参数,得到结果不同
$this->uri->segment(3);

改变浏览器中的URL,结果也不同

总之,$this->uri->segment(int)是获取URL对应段中内容的函数
Views
在views目录下创建example1.php文件,写入
<body>
<div id="container">
<h1>Countries</h1>
<div id="body">
<?php
foreach($results as $data) {
echo $data->country ."<br>";
}
?>
<p><?php echo $links; ?></p>
</div>
<p class="footer">Page rendered in <strong>0.0043</strong> seconds</p>
</div>
</body>
其中的$results与控制器中的$result['results']是同一个。
运行
在浏览器中打开http://localhost/index.php/demo/countries/即可运行
