
Read Time: 14 mins url-selector#selectionChanged"> العربية/عربي Deutsch English Español پارسی Italiano Wikang Tagalog українська мова 中文(简体) 中文(繁體)
I can remember years ago, when I first began coding in PHP and MySQL, how excited I was the first time I got information from a database lớn show up in a web browser.
Bạn đang xem: How to paginate data with php
For someone who had little database & programming knowledge, seeing those table rows show up onscreen based on the darkedeneurope.com I wrote (okay, so I copied an example from a book) gave me a triumphant feeling. I may not have fully understood all the magic at work back then, but that first success spurred me on to lớn bigger & better projects.
While my màn chơi of exuberance over databases may not be the same as it once was, ever since my first "hello world" encounter with PHP và MySQL I"ve been hooked on the power of making things simple & easy to lớn use.
As a developer, one problem I"m constantly faced with is taking a large set of information và making it easy to lớn digest. Whether it"s a large company"s client menu or a personal MP3 catalog, having khổng lồ sit and stare at rows upon rows upon rows of data can be discouraging and frustrating. What can a good developer do? Paginate!
Looking for a Quick Solution?
If you"re looking for a quick solution, there"s a great collection of pagination scripts & helpers over at Envato Market.
For example, try out the ZPager PHP pagination class. It makes it easy khổng lồ generate listing pagination links and customize them in just a few clicks. ZPager supports Bootstrap, MySQL, and Smarty Template Engine, & it also lets you use SEO-friendly URLs.



1. Pagination
Pagination is essentially the process of taking a mix of results & spreading them out over pages lớn make them easier to view.

I realized early on that if I had 5,000 rows of information khổng lồ display, not only would it be a headache for someone khổng lồ try and read, but most browsers would take an mạng internet eternity (i.e. More than about five seconds) lớn display it.
To solve this, I created a simple, flexible, and easy-to-use PHP class that I could use for pagination in all my projects.
2. The Database
Gotta love MySQL. No offense lớn the other database systems out there, but for me, all I need is MySQL. And one great feature of MySQL is that they give you some không lấy phí sample databases lớn play with at https://dev.mysql.com/doc/#sampledb.
For my examples, I"ll be using the world database (~90k zipped), which contains over 4,000 records to play with, but the beauty of the PHP script we"ll be creating is that it can be used with any database. Now I think we can all agree that if we decided not lớn paginate our results, we would over up with some very long và unwieldy results lượt thích the following:

So let"s gets down to breaking up our data into easy-to-digest bites like this:

Beautiful, isn"t it? Once you drop the pagination class into your darkedeneurope.com, you can quickly & easily transform a huge phối of data into easy-to-navigate pages with just a few lines of darkedeneurope.com. Really.
3. The Paginator
This example will be composed of two scripts: the reusable paginator class and the index tệp tin that will display the table items và controls.
Paginator.class.php
The paginator class will have only two methods và the constructor. We will build it gradually, explaining each step as we move forward.
This definition only sets the paginator required thành viên variables. Since this is a helper class và it"s destined for pagination only, it will rely on a valid connection to the MySQL server & an already defined query, to lớn which we will append the parameters necessary to lớn paginate the results. We"ll start with the constructor method.
_conn = $conn; $this->_query = $query; $rs= $this->_conn->query( $this->_query ); $this->_total = $rs->num_rows; }Quite simple, right? This method only sets the object"s database connection & the necessary query. After that, it calculates the total number of rows retrieved by that query without any limit or skip parameters. This total is necessary to create the links for the paginator.
Note that, for simplicity, we are not doing error checking or any other validation of the given parameters, but in a real-world application, these checks will be necessary.
Xem thêm: Guide On Php Fopen : Master Fopen Php And Other Functions, Opens File Or Url
Retrieving Results
Now, let"s create the method that will actually paginate the data and return the results.
_limit = $limit; $this->_page = $page; if ( $this->_limit == "all" ) $query = $this->_query; else $query = $this->_query . " LIMIT " . ( ( $this->_page - 1 ) * $this->_limit ) . ", $this->_limit"; $rs = $this->_conn->query( $query ); while ( $row = $rs->fetch_assoc() ) $results<> = $row; $result = new stdClass(); $result->page = $this->_page; $result->limit = $this->_limit; $result->total = $this->_total; $result->data = $results; return $result;}Let"s analyze this one step at a time. First, we set the limit and page parameters, which by default are set khổng lồ 10 & 1 respectively. Then, we check if the user requires a given number of rows or all of them. Based on this & the page parameter, we mix the LIMIT term of the query. Chú ý that we take one from the page number because our script counts from 1 instead of from 0.
After this, we simply evaluate the query and get the results. Finally, we create a new results object which contains the limit, page, và total parameters of the executed query, as well as the data for each of the retrieved rows.
Displaying Pagination Links
Now, let"s write the method used lớn get the pagination links.
_limit == "all" ) return ""; $last = ceil( $this->_total / $this->_limit ); $start = ( ( $this->_page - $links ) > 0 ) ? $this->_page - $links : 1; $end = ( ( $this->_page + $links ) _page + $links : $last; $html = ""; $class = ( $this->_page == 1 ) ? "disabled" : ""; $html .= ""; if ( $start > 1 ) $html .= ""; $html .= "..."; for ( $i = $start ; $i _page == $i ) ? "active" : ""; $html .= ""; } if ( $end ..."; $html .= ""; } $class = ( $this->_page == $last ) ? "disabled" : ""; $html .= ""; $html .= ""; return $html;}This is a rather long method, so let"s look over it in more detail.
First, we evaluate if the user requires a given number of liên kết or all of them. If the user is requesting all links, then we simply return an empty string, since no pagination is required.
After this, we calculate the last page based on the total number of rows available và the items required per page.
Then, we take the link parameter, which represents the number of links to display below & above the current page, và calculate the start and end link to create.
Next, we create the opening tag for the list & set the class of it with the các mục class parameter. We also add the "previous page" link—note that for this link, we check if the current page is the first, và if so, we mix the disabled property of the link. We also display a liên kết to the first page và an ellipsis symbol in case the start links is not the first one.
Next, we showroom the link below & above the current page, based on the previously calculated start and end parameters. In each step, we evaluate the current page against the links page displayed and set the active class accordingly.
After this, we display another ellipsis symbol và the liên kết to the last page, in case the end link is not the last one.
Finally, we display the "next page" liên kết and mix the disabled state when the user is viewing the last page, close the list, và return the generated HTML string.
That"s all there is khổng lồ the Paginator class! Of course, we could add setters và getters for the database connection, limit, page, query, và total parameters, but for simplicity we"ll keep it this way.
4. The Index Page
Now we"ll create the index.php file, which is in charge of using the Paginator class and displaying the data. First, let me show you the base HTML.