PHP 框架: CodeIgniter 分页教程

来源:互联网 发布:开关电源仿真软件saber 编辑:程序博客网 时间:2024/05/16 12:54

 有些时候,你可能需要把数据库查询所得到的一篇文章或一组结果拆分成多页。在这时,你将需要写某种分页脚本。这对于从没有做过这个的开发者来说还是有一点难度的,但使用 CodeIgniter 却是轻而易举就能完成的。
        CodeIgniter 具有非常容易使用的分页类。在本教程中我会做一个从数据库返回一组结果并分页这些结果的简单例子。我将使用最新版本的 CI,写这篇文章时的版本是 1.5.1 。分页类并没有修改(至少我认为没有),用最新的稳定版框架总是好的。现在,让我们开始吧。

        配置和数据库设置

        很好,一切正常,当我们开始写一个 CI 应用程序时,我们要设置很多东西。我们首先打开 config.php 文件(可在 /system/application/config/ 中找到)。在这里我们将输入站点根 URL。这是我的设置:

你的设置可能会和我的略有不同。

        这个应用程序将使用一个数据库,所以我们下一步的工作是创建数据库,然后再以 CI 访问我们的数据库。要做到这一点请打开 database.php,这也定位在你的 config 文件夹中,并填写必要的信息,以便连接到你的数据库。您可以下载“例子代码”:如果你愿意可以使用例子代码和我的例子数据库。这将创建一个名为“christian_books”的表,并插入一些测试数据。同时,我想你现在可以猜一猜分页后是什么样?如果你猜对了一些“Christian Books”,你将是正确的。

        控制器

        我们的基本配置文件和数据库设置已经完成,现在我们需要创建一个控制器。我将它命名为“books.php”,并且它将包含下列代码:

如果你读过我最近写的介绍 CI的系列文章,那么,你将在这里看到许多很熟悉的内容。如果你没读过并且是新手,要想感受 CI 这种自由的话,要阅读上面的这篇文章,然后再回来继续看下面的内容。如果你已经加快了学习速度,那么,让我们继续看看上述代码更详细的描述。
        首先,我们在构造函数中装载 URL 辅助函数和数据库。当然,你不一定要创建一个构造函数并装载这些辅助函数,因为它可以很容易的在控制器中的其它函数/方法中装载,但是,如果辅助函数将用于控制器中的大多数/所有方法的话,我通常倾向于创建一个构造函数并把它们放在里面。
        其次,我们创建了一个名为 index() 的方法。这是一个非常基本的应用程序,正因如此,我们将只需要这种单一的方法,使我们装载分页类,模型和 HTML 表格类(我们稍后将讨论的内容) 。
        让我们开始吧!你会看到非常简单的使用分页类的方法。首先,我们配置要分页页面的 URL:

这个 base_url() 函数不要与 $config[] 数组中的 base_url 相混淆。该 base_url() 函数来自 URL 辅助函数并且它代表整个应用程序的 URL。在上述代码中,连接到 base_url() 后面的内容是要分页页面的地址。
        然后,我们设置数据库中的总行数:

 

这个函数返回数据库中的所有行,如果你运行一个特定查询将返回某些行,并不一定是所有的行,然后,你可能会使用在记录辅助函数中的 $query->num_row() 函数。
        $config['per_page'] 变量简单地告诉分页类每页显示多少条记录。$config['full_tag_open'] 和 $config['full_tag_close'] 变量说明使用什么标签包围分页链接。
        接下来,我们装载模型,我们将执行其中的一个方法:get_books()。它有两个参数,limit,这决定了每页显示多少项目,offset,它表示从哪行开始返回记录。你会发现,第一个参数(limit)从 $config['per_page'] 变量中取值,而第二个参数则通过 URL 辅助函数,从 URL 的第三段中取值:$this->uri->segment(3)。后者是这里非常有趣的原因。CI 的 URL 通常采取以下形式,www.your-site.com/index.php/class/function/ID,所以大家可以看到第三段(index.php 的后面)代表 ID。所以允许采用如下的 URL:

        http://localhost/~yannick/pagination/index.php/books/index/10

        URL 第三段的 10 将被插入到我们模型函数的第二个参数中:get_books(5, 10),它表示偏移量(offset)。因此,我们的结果将返回数据库中前 10 条记录的后 5 条记录(因为根据前面的代码,我们每页显示 5 条记录)。非常妙,对不对?好了,我们先在停在这里休息一下,更详细的内容将在下一节中。
        现在,这里有一些新东西。在这里,我们装载 HTML 表格类,这是新添加到 CI 1.5.0 版本中的。这个类允许你从数组或数据库结果中生成 HTML 表格。你可以进行相当多的定制,但在这个例子中,我使用他基本形式中的一种:我明确的指明表格的头部应该是什么。

 

如果我没有指明这一点,HTML 表格类将使用它们在数据库表中的名字作为表名。因此,举例来说,如果你的数据库表中有一个列名为“book_id”,则表格类将使用“book_id”。如果你不想它这样显示的话,则上述代码片断允许你指定一个更可读的字段名。
        最后,我们装载“视图”,并传递给它我们将用到的任何数据。都做好后,我们的控制器就完成了。现在,让我们来看看我们的模型,看看怎样在分页中发挥它的威力。

        模型

        OK,这时候模型就开始重新调用你数据库里的信息了。在这个分页教程中,我们的模型将包含一个方法,它基于页面上的用户请求,从数据库中获取正确的结果。正如你所看到的,控制器方法有两个参数,一个 limit 和另一个 offset。然后,我们创建一个文件,命名为“books_model.php”,并在文件中输入下列代码:

 

 

大家可以看到,我们的模型‘books_model‘和方法 get_books(),本教程中包含了一个填充了图书记录的数据库,我们希望取得这些图书并显示在屏幕上。你会注意到我们调用 get_books() 的两个参数,分别是 $num 和 $offset。 $num 指明从数据库中取得的记录数,$offset 指明将从哪开始获取记录。

 


上面的代码将产生下面的 MySQL 查询(举例):

 

 

 

 

 

5 代表 $num,10 代表 $offset。以上就是传给模型的所有内容了。我们存储这些结果在一个名为 $query 的变量中,然后把变量返回给调用它的方法。把这些结合起来,我们的模型就写完了。
        我们已经完成了 2/3 了,最后事情是,我们要创建视图。

        视图

        记住,一个视图就是一个简单的 Web 页面或页面片段。所以,在这里我们的视图是一个在表格里显示图书的 Web 页面。让我们来看看代码:

 

 

 

你可能会想,“这当然不能这么简单。”是的,这只是为本教程创建的视图。

 

 

首先,把从模型中得到的结果传递到 generate() 方法中,这样,我们将创建显示图书表格的 HTML 代码。

 

接下来,我们分页类中的 create_links() 方法是最有用的,它创建各页页码的链接,包括“下一页”和“上一页”的链接。它看起来类似这样:

        « First  < 1 2 3 4 5 >  Last »

        现在访问你的页面,并在显示页码的地方开心的玩一玩。你也可以从一页切换到另一页,看看 URL 是怎样变化的,并且 URL 的第三段表示显示在表格中结果的偏移量。

        总结

        好了,上面我简单介绍了分页类,正如你看到的,添加分页功能到你的 CI 应用程序并不难。我也介绍了在 1.5.0 版本中新添加的 HTML 表格类,并且它也不是很难。这个类库使我们可以快速的创建 HTML 表格,以显示我们的结果。
        就这样了,我希望你在享受本教程的同时,会发现它内容翔实并对你有帮助。如果你有兴趣学习如何在没有 CI 框架帮助的情况下,在 PHP 中做分页程序,那么,我建议你看看 Jonathan Sampson 制作的分页视频.
        世界和平,上帝保佑。

下载例子代码: ci_pagination_tut.zip

原文:http://godbit.com/article/pagination-with-code-igniter
翻译:CodeIgniter 中国
鸣谢:CodeIgniter 中国开发者社区的朋友们!

 

 

 

 

英文原文如下:

 

 

Pagination with Code Igniter

10 comments | Posted: 12 February 07 in Tutorials, by Yannick Lyn Fatt

There are times when you may have to either split an article or a set of results lets say from a database query to span multiple pages. In times like those you will need to write some sort of pagination script. This can be a little overwhelming for developers who have never done something like that before, but with Code Igniter its a cinch to do.

Code Igniter comes with a Pagination class that is pretty easy to use and implement. In this tutorial I’ll do a quick example of returning a set of results from a database and paginating those results. I’ll be using the latest version of CI, which, as of this article is version 1.5.1. While the Pagination class hasn’t changed from the previous versions (at least not to my knowledge), it’s always good to use the latest stable version of the framework. So let’s get started.

Configuration and Database Setup

Okay, as usual, whenever we are starting a CI application, there are a few things we have to setup. First we open our config.php file (which can be found in /system/application/config/). Here we will enter our Base Site URL. This is what I set mine as:

 

 

For you it will probably be something slightly different.

This application will be using a database, so our next step is to create that database and then give CI access to our database. To do this open database.php, which is also located in your config folder and put in the necessary information to connect to your database. You may download the “sample code”: for this tutorial and use my example database if you would like. It will create a table called ‘christian_books‘ and insert some test data to help with this tutorial. With that said I suppose you can now guess what we will be paginating. If you guessed some Christian Books then you would be correct.

The Controller

With our basic configuration files and database setup now complete we’ll need to create a controller. I will call mine ‘books.php‘ and it will contain the following code:

 

 

If you read through the Introduction to CI series I recently did then you may notice a few things here that are familiar. If you didn’t and are new to CI then feel free to go through that three part series and then return to this one. If you are already up to speed, then let us continue and have a look through the code above in more detail.

First we have our constructor in which we load our URL Helper and Database. Of course, you don’t have to create a constructor and load those helpers, as it you can easily load them in other the functions/methods in your controller, however, if the helpers are going to be used throughout most/all of the methods in the controller then I usually prefer to create a constructor and place them there.

Next we created one method called index(). This is a pretty basic application and as such we’ll only be needing this single method in which we loaded the pagination class, model and html table class (which we will discuss a little later in this tutorial).

Let us begin with the Pagination class, which, as you will see is very simple to use. First we configure the base URL of the web page to be paginated:

 

 

 

This base_url is not to be confused with the base_url() function I used in the assignment of the $config[] array. The base_url() function comes from the URL Helper and it represents the URL for the application on a whole. Concatenated to that is the remainder of the URL necessary to reference the web page to be paginated.

Next we configure the total number of rows in our database:

 

 

 

Since I am returning all the rows in my database then this function will do fine, however, if you were running a specific query that will return some and not necessarily all the rows then you would probably want to use the $query->num_rows() function found in the set of result helper functions.

The $config['per_page'] variable simply tells the Pagination Class how many results to display on each page. And the $config['full_tag_open'] and $config['full_tag_close'] variables state what tags to use to surround the pagination links.

Next we load our model, which we will create shortly and execute one of its methods, get_books(). It takes in two arguments, the limit, which determines how many items to display on each page and an offset which will tell it what row to start returning results from. You will notice that the first argument (the limit) gets it’s value from the $config['per_page'] variable, while, the second argument gets its value from the 3rd segment of the URL via another URL helper function, $this->uri->segment(3). The latter is very interesting and here’s why. CI’s URLs usually take the following form, www.your-site.com/index.php/class/function/ID, so as you can see the 3rd segment (after index.php) represents the ID. So lets take for example the following URL:

http://localhost/~yannick/pagination/index.php/books/index/10

The 3rd segment would be 10 and when inserted as the 2nd argument of our model function get_books(5, 10) it represents the offset. So in other words our results will return the next 5 records (since our results per page is 5, based on the code shown earlier) after the first 10 records in our database. Pretty neat, right? Okay, let’s stop here for now as we will talk about this in a little more detail the next section.

Now here’s something new. Here we are loading the HTML Table Class, which was a new addition to CI in Version 1.5.0. This class allows you to generate HTML tables from arrays or database results. There are quite a few customizations you can make, however for the purposes of this example I’m using it in it’s basic form with one exception, I’m specifying explicitly what the headings of the table should be.

 

 

 

 

If I didn’t specify this, the HTML Table Class would use the table names as they are in the database table. So if for example you had a column name ‘book_id‘ in your database table, then the table class would use ‘book_id‘. Chances are, you don’t want it to be displayed like that, so the above snippet of code allows you to specify a more readable name for the column.

Lastly, we load our ‘View’ and pass it any necessary data that we will use. And there you have it, our controller is now done. Let us now take a look at our model and see what roll it plays in pagination.

The Model

Ok, so you may recall that the Model works with information in your database. In this Pagination tutorial our model will contain a method that deals with retrieving the correct results from our database based on the page that the user requested. As you saw in the controller the method will have two arguments, one for the limit and the other for the offset. So we create a file called ‘books_model.php‘ and the code in that file will be as follows:

 

 

 

 

As you can see, we called our model ‘books_model‘ and our method get_books(), since this tutorial contains a database filled with books and we want to get those books and display them on screen. You will notice we called the two arguments to get_books(), $num and $offset respectively. $num specifies the number of results to retrieve from the database and $offset specifies where it should start retrieving results from.

 

 

The above code will produce the following query in MySQL (for example):

 

 

Five (5) represents $num and Ten (10) represents $offset. That’s all there is to it. We store those results in a variable called $query and then return that variable to anything that calls that method. And with that our model is now complete.

We are 2/3 of the way there. The last thing we need to do is to create our view.

The View

Remember a View is simply a web page or a page fragment. So our view in this case is a web page that displays our books in a table. Let’s have a look at the code:

 

 

You may be thinking, ‘Surely that can’t be it.’ Yeah that’s all there is to creating the view for this tutorial.

 

 

By passing the results we obtained from our model to the generate() method it will create the HTML necessary to display our table containing our books.

 

 

 

Next we have our Pagination create_links() method, which does exactly what it says. It creates the links to the various pages including ‘Next’ and ‘Previous’ links. It will look a little something like this:

« First < 1 2 3 4 5 > Last »

Now visit your web page and have fun playing around with the Pagination. Also as you switch from page to page, watch how the URL changes and the 3rd segment represents the offset of the results displayed in the table.

Summary

Well there you have it, a quick introduction to the Pagination Class and as you have seen it’s not that difficult to add pagination to your application in CI. You were also introduced to the new HTML Table Class added in version 1.5.0. Again it wasn’t too difficult. With this Library we were able to whip up a quick HTML table to display our results.

Well that’s it for now, I hope you enjoyed this tutorial and found it informative and helpful. If you are interested in learning how to do Pagination in PHP without the help of the CI Framework, then I would recommend you watch Jonathan Sampson’s Pagination screencast.

Peace and God bless.

Download Code: ci_pagination_tut.zip

原创粉丝点击