PHP paging display production details

Source: Internet
Author: User
Tags pear
1. forward pagination is a very common method for browsing and displaying large amounts of data. it is one of the most common events in web programming. For veterans of web programming, writing such code is as natural as breathing, but for beginners, they often have no clue about this issue. Therefore, I wrote this article to explain this issue in detail, we strive to make friends who have read this article understand the principle and implementation methods of paging display. This article is suitable for beginners to read. all sample code uses 1. Preface

Paging display is a very common method for browsing and displaying large amounts of data. it is one of the most common events in web programming. For veterans of web programming, writing such code is as natural as breathing, but for beginners, they often have no clue about this issue. Therefore, I wrote this article to explain this issue in detail, we strive to make friends who have read this article understand the principle and implementation methods of paging display. This article is suitable for beginners. all sample code is written in php.

2. Principles

The so-called paging display means that the result set in the database is manually divided into segments for display. here two initial parameters are required:

How many records per page ($ PageSize )?
What is the current page ($ CurrentPageID )?

Now, you only need to give me another result set, so that I can display a specific result.
Other parameters, such as the previous page ($ PReviousPageID), Next page ($ NextPageID), and total page ($ numPages), can all be obtained based on the front.
Take the MySQL database as an example. if you want to extract some content from the table, you can use the SQL statement: select * from table limit offset, rows. Take a look at the following SQL statements and try to find the rule rate.

First 10 records: select * from table limit 0, 10
11th to 20 records: select * from table limit 10, 10
21st to 30 records: select * from table limit 20, 10
......

This set of SQL statements is the SQL statement used to retrieve data of each page in the table when $ PageSize = 10. we can summarize this template:

Select * from table limit ($ CurrentPageID-1) * $ PageSize, $ PageSize

Use this template to compare the corresponding values with the preceding SQL statements to see if this is the case. After solving the most important problem of how to obtain data, the rest is simply passing parameters, constructing appropriate SQL statements, and then using php to obtain data from the database and display it. I will describe the code below.

3. simple code
Please read the following code in detail and debug and run it once. you 'd better modify it once and add your own functions, such as search.

// Establish a database connection
$ Link = mysql_connect ("localhost", "mysql_user", "mysql_passWord ")
Or die ("cocould not connect:". mysql_error ());
// Obtain the current page number
If (isset ($ _ GET ['Page']) {
$ Page = intval ($ _ GET ['Page']);
}
Else {
$ Page = 1;
}
// Number of pages per page
$ PageSize = 10;
// Obtain the total data volume
$ SQL = "select count (*) as amount from table ";
$ Result = mysql_query ($ SQL );
$ Row = mysql_fetch_row ($ result );
$ Amount = $ row ['amount'];
// Count the total number of pages
If ($ amount ){
If ($ amount <$ page_size) {$ page_count = 1;} // if the total data volume is less than $ PageSize, there is only one page
If ($ amount % $ page_size) {// Retrieve the total data volume divided by the remainder of each page
$ Page_count = (int) ($ amount/$ page_size) + 1; // if there is a remainder, the number of pages equals the total data volume divided by the result of each page number and then adds one
} Else {
$ Page_count = $ amount/$ page_size; // if there is no remainder, the number of pages equals the total data volume divided by the result of each page
}
}
Else {
$ Page_count = 0;
}

// Flip link
$ Page_string = '';
If ($ page = 1 ){
$ Page_string. = 'Page 1 | previous page | ';
}
Else {
$ Page_string. = 'Page 1 | previous page | ';
}
If ($ page = $ page_count) | ($ page_count = 0 )){
$ Page_string. = 'next page | last page ';
}
Else {
$ Page_string. = 'next page | last page ';
}
// Obtain data and return results in two-dimensional array format
If ($ amount ){
$ SQL = "select * from table order by id desc limit". ($ page-1) * $ page_size. ", $ page_size ";
$ Result = mysql_query ($ SQL );
 
While ($ row = mysql_fetch_row ($ result )){
$ Rowset [] = $ row;
}
} Else {
$ Rowset = array ();
}
// The code that does not contain the display result is not in the scope of the discussion. you only need to use foreach to easily display the result using the two-dimensional array.
?>

4. OO-style code
The database connection in the following code uses the pear db class for processing.

// FileName: Pager. class. php
// Paging class. this class is only used to process the data structure and is not used to process the display.
Class Pager
{
Var $ PageSize; // Number of pages per page
Var $ CurrentPageID; // Current page number
Var $ NextPageID; // Next page
Var $ PreviousPageID; // Previous Page
Var $ numPages; // The total number of pages.
Var $ numItems; // The total number of records
Var $ isFirstPage; // whether the first page is displayed
Var $ isLastPage; // whether it is the last page
Var $ SQL; // SQL query statement
 
Function Pager ($ option)
{
Global $ db;
$ This-> _ setOptions ($ option );
// Total number of entries
If (! Isset ($ this-> numItems ))
{
$ Res = $ db-> query ($ this-> SQL );
$ This-> numItems = $ res-> numRows ();
}
// Total number of pages
If ($ this-> numItems> 0)
{
If ($ this-> numItems <$ this-> PageSize) {$ this-> numPages = 1 ;}
If ($ this-> numItems % $ this-> PageSize)
{
$ This-> numPages = (int) ($ this-> numItems/$ this-> PageSize) + 1;
}
Else
{
$ This-> numPages = $ this-> numItems/$ this-> PageSize;
}
}
Else
{
$ This-> numPages = 0;
}
   
Switch ($ this-> CurrentPageID)
{
Case $ this-> numPages = 1:
$ This-> isFirstPage = true;
$ This-> isLastPage = true;
Break;
Case 1:
$ This-> isFirstPage = true;
$ This-> isLastPage = false;
Break;
Case $ this-> numPages:
$ This-> isFirstPage = false;
$ This-> isLastPage = true;
Break;
Default:
$ This-> isFirstPage = false;
$ This-> isLastPage = false;
}
   
If ($ this-> numPages> 1)
{
If (! $ This-> isLastPage) {$ this-> NextPageID = $ this-> CurrentPageID + 1 ;}
If (! $ This-> isFirstPage) {$ this-> PreviousPageID = $ this-> CurrentPageID-1 ;}
}
   
Return true;
}
 
/***
*
* Database connection to the returned result set
* When the result set is large, you can directly use this method to obtain the database connection and traverse the database outside of the class. this reduces the overhead.
* If the result set is not large, you can directly use getPageData to obtain results in two-dimensional array format.
* The getPageData method also calls this method to obtain the result.
*
***/
 
Function getDataLink ()
{
If ($ this-> numItems)
{
Global $ db;
     
$ PageID = $ this-> CurrentPageID;
     
$ From = ($ PageID-1) * $ this-> PageSize;
$ Count = $ this-> PageSize;
$ Link = $ db-> limitQuery ($ this-> SQL, $ from, $ count); // use the Pear DB: limitQuery method to ensure database compatibility
     
Return $ link;
}
Else
{
Return false;
}
}
 
/***
*
* Returns the result set in two-dimensional array format.
*
***/
 
Function getPageData ()
{
If ($ this-> numItems)
{
If ($ res = $ this-> getDataLink ())
{
If ($ res-> numRows ())
{
While ($ row = $ res-> fetchRow ())
{
$ Result [] = $ row;
}
}
Else
{
$ Result = array ();
}
       
Return $ result;
}
Else
{
Return false;
}
}
Else
{
Return false;
}
}
 
Function _ setOptions ($ option)
{
$ Allow_options = array (
'Pagesize ',
'Currentpageid ',
'SQL ',
'Numitems'
);
   
Foreach ($ option as $ key => $ value)
{
If (in_array ($ key, $ allow_options) & ($ value! = Null ))
{
$ This-> $ key = $ value;
}
}
   
Return true;
}
}
?>
// FileName: test_pager.php
// This is a simple sample code. the code for establishing a database connection using the pear db class is omitted in the front.
Require "Pager. class. php ";
If (isset ($ _ GET ['Page'])
{
$ Page = (int) $ _ GET ['Page'];
}
Else
{
$ Page = 1;
}
$ SQL = "select * from table order by id ";
$ Pager_option = array (
"SQL" => $ SQL,
"PageSize" => 10,
"CurrentPageID" => $ page
);
If (isset ($ _ GET ['numitems '])
{
$ Pager_option ['numitems '] = (int) $ _ GET ['numitems'];
}
$ Pager = @ new Pager ($ pager_option );
$ Data = $ pager-> getPageData ();
If ($ pager-> isFirstPage)
{
$ Turnover = "homepage | previous page | ";
}
Else
{
$ Turnover = "numItems." '> homepage | PreviousPageID. "& numItems =". $ pager-> numItems. "'> Previous Page | ";
}
If ($ pager-> isLastPage)
{
$ Turnover. = "next page | last page ";
}
Else
{
$ Turnover. = "NextPageID. "& numItems = ". $ pager-> numItems. "'> Next Page | numPages. "& numItems = ". $ pager-> numItems. "'> last page ";
}
?>

There are two areas to note:

This class only processes data and is not responsible for displaying the data, because I feel that it is a little effort to put the data processing and result display in a class. When the display status and requirements are changeable, it is better to handle the problem based on the results given by the class. the better way is to display different pages based on the Pager class inheriting a subclass of its own, for example, to display the user page list, you can:

Class MemberPager extends Pager
{
Function showMemberList ()
{
Global $ db;
   
$ Data = $ this-> getPageData ();
// Code for displaying the result
//......
}
}
/// Call
If (isset ($ _ GET ['Page'])
{
$ Page = (int) $ _ GET ['Page'];
}
Else
{
$ Page = 1;
}
$ SQL = "select * from members order by id ";
$ Pager_option = array (
"SQL" => $ SQL,
"PageSize" => 10,
"CurrentPageID" => $ page
);
If (isset ($ _ GET ['numitems '])
{
$ Pager_option ['numitems '] = (int) $ _ GET ['numitems'];
}
$ Pager = @ new MemberPager ($ pager_option );
$ Pager-> showMemberList ();
?>

The second thing to note is the compatibility of different databases. the way to intercept a piece of results in different databases is different.
Mysql: select * from table limit offset, rows
Pgsql: select * from table limit m offset n
......
Therefore, you must use the limitQuery method of the pear db class to obtain results in the class.

OK. You don't think it is a waste of time to finish reading these words.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.