21,886
社区成员
发帖
与我相关
我的任务
分享
$config['base_url'] = "http://localhost/~yannick/pagination/";
你的设置可能会和我的略有不同。class Books extends Controller {
function __construct() {
parent::Controller();
$this->load->helper('url');
$this->load->database();
}
function index() {
// load pagination class
$this->load->library('pagination');
$config['base_url'] = base_url().'index.php/books/index/';
$config['total_rows'] = $this->db->count_all('christian_books');
$config['per_page'] = '5';
$config['full_tag_open'] = '<p>';
$config['full_tag_close'] = '</p>';
$this->pagination->initialize($config);
//load the model and get results
$this->load->model('books_model');
$data['results'] = $this->books_model->get_books($config['per_page'],$this->uri->segment(3));
// load the HTML Table Class
$this->load->library('table');
$this->table->set_heading('ID', 'Title', 'Author', 'Description');
// load the view
$this->load->view('books_view', $data);
}
}
如果你读过我最近写的介绍 CI的系列文章,那么,你将在这里看到许多很熟悉的内容。如果你没读过并且是新手,要想感受 CI 这种自由的话,要阅读上面的这篇文章,然后再回来继续看下面的内容。如果你已经加快了学习速度,那么,让我们继续看看上述代码更详细的描述。$config['base_url'] = base_url().'index.php/books/index/';
这个 base_url() 函数不要与 $config[] 数组中的 base_url 相混淆。该 base_url() 函数来自 URL 辅助函数并且它代表整个应用程序的 URL。在上述代码中,连接到 base_url() 后面的内容是要分页页面的地址。$config['total_rows'] = $this->db->count_all('christian_books');
这个函数返回数据库中的所有行,如果你运行一个特定查询将返回某些行,并不一定是所有的行,然后,你可能会使用在记录辅助函数中的 $query->num_row() 函数。$this->table->set_heading('ID', 'Title', 'Author', 'Description');
如果我没有指明这一点,HTML 表格类将使用它们在数据库表中的名字作为表名。因此,举例来说,如果你的数据库表中有一个列名为“book_id”,则表格类将使用“book_id”。如果你不想它这样显示的话,则上述代码片断允许你指定一个更可读的字段名。class books_model extends Model {
function __construct(){
parent::Model();
}
function get_books($num, $offset) {
$query = $this->db->get('christian_books', $num, $offset);
return $query;
}
}
大家可以看到,我们的模型‘books_model‘和方法 get_books(),本教程中包含了一个填充了图书记录的数据库,我们希望取得这些图书并显示在屏幕上。你会注意到我们调用 get_books() 的两个参数,分别是 $num 和 $offset。 $num 指明从数据库中取得的记录数,$offset 指明将从哪开始获取记录。$query = $this->db->get('christian_books', $num, $offset);
上面的代码将产生下面的 MySQL 查询(举例):SELECT * FROM christian_books LIMIT 10, 5
5 代表 $num,10 代表 $offset。以上就是传给模型的所有内容了。我们存储这些结果在一个名为 $query 的变量中,然后把变量返回给调用它的方法。把这些结合起来,我们的模型就写完了。<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-us" lang="en-us">
<head>
<meta http-equiv="content-type" c />
<link rel="stylesheet" href='<?php echo base_url(); ?>css/main.css' type="text/css" media="screen, projection" />
<title>CodeIgniter Pagination Tutorial</title>
</head>
<body>
<h1>Christian Books</h1>
<?php echo $this->table->generate($results); ?>
<?php echo $this->pagination->create_links(); ?>
</body>
</html>
你可能会想,“这当然不能这么简单。”是的,这只是为本教程创建的视图。$this->table->generate($results);
首先,把从模型中得到的结果传递到 generate() 方法中,这样,我们将创建显示图书表格的 HTML 代码。$this->pagination->create_links();
接下来,我们分页类中的 create_links() 方法是最有用的,它创建各页页码的链接,包括“下一页”和“上一页”的链接。它看起来类似这样: