Home  >  Article  >  Backend Development  >  Detailed explanation of PHP pagination display_PHP tutorial

Detailed explanation of PHP pagination display_PHP tutorial

WBOY
WBOYOriginal
2016-07-22 09:02:451622browse

 1. Foreword

 Paging display is a very common method of browsing and displaying large amounts of data, and it is one of the most commonly processed events in web programming. For veterans of web programming, writing this kind of code is as natural as breathing, but for beginners, they are often confused about this issue, so I specially wrote this article to explain this issue in detail, and strive to let readers Friends who have finished this article will have some understanding of the principles and implementation methods of paging display. This article is suitable for beginners to read, and all sample codes are written in PHP.

 2. Principle

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

How many records per page ($PageSize)?

 What page is the current page ($CurrentPageID)?

 Now as long as you give me another result set, I can display a specific result.

As for other parameters, such as: previous page ($PReviousPageID), next page ($NextPageID), total number of pages ($numPages), etc., they can all be obtained based on the previous things.

Taking the MySQL database as an example, if you want to intercept a certain piece of content from the table, the sql statement can be used: select * from table limit offset, rows. Take a look at the following set of SQL statements and try to find the rules.

 The first 10 records: select * from table limit 0,10

 Records 11 to 20: select * from table limit 10,10

 Records 21 to 30: select * from table limit 20,10

 ……

This set of sql statements is actually the sql statement that fetches data from each page in the table when $PageSize=10. We can summarize such a template:

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

  Take this template and substitute the corresponding values ​​​​and compare it with the above set of SQL statements to see if that is the case. After solving the most important problem of how to obtain the data, all that is left is to pass the parameters, construct the appropriate SQL statement and then use PHP to obtain the data from the database and display it. Below I will explain it with specific code.

 3. Simple code

Please read the following code in detail, debug and run it yourself. It is best to modify it once and add your own functions, such as search, etc.

 

  // Establish database connection

 $link = mysql_connect("localhost", "mysql_user", "mysql_passWord")

 or die("Could not connect: " . mysql_error());

  // Get the current page number

 if( isset($_GET['page']) ){

 $page = intval( $_GET['page'] );

 }

 else{

 $page = 1;

 }

  // Quantity per page

 $PageSize = 10;

  // Get the total data amount

 $sql = "select count(*) as amount from table";

 $result = mysql_query($sql);

 $row = mysql_fetch_row($result);

 $amount = $row['amount'];

  // Count how many pages there are in total

 if( $amount ){

 if( $amount < $page_size ){ $page_count = 1; } //If the total data amount is less than $PageSize, then there is only one page

 if( $amount % $page_size ){ //Take the remainder after dividing the total data amount by the number of pages

 $page_count = (int)($amount / $page_size) + 1; //If there is a remainder, the number of pages is equal to the total data amount divided by the number of pages, rounded up and plus one

 }else{

 $page_count = $amount / $page_size; //If there is no remainder, the number of pages is equal to the total data amount divided by the number of pages per page

 }

 }

 else{

 $page_count = 0;

 }

  // Page turning link

 $page_string = '';

 if( $page == 1 ){

 $page_string .= 'First page|Previous page|';

 }

 else{

  $page_string .= 'First page|Previous page< /a>|';
}

 if( ($page == $page_count) || ($page_count == 0) ){

 $page_string .= 'Next page|Last page';

 }

 else{

  $page_string .= 'Next page|';
}

  // Get data and return the result 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();

 }

  // There is no code for displaying results, so that is beyond the scope of discussion. As long as you use foreach, you can easily display the results using the obtained two-dimensional array

  ?>

 4. OO style code

 The database connection in the following code is processed using the pear db class

 

  // FileName: Pager.class.php

  //Paging class, this class is only used to process the data structure and is not responsible for processing the display

 Class Pager

 {

 var $PageSize; //Number of each page

 var $CurrentPageID; //Current page number

 var $NextPageID; //Next page

 var $PreviousPageID; //Previous page

 var $numPages; //Total number of pages

 var $numItems; //Total number of records

 var $isFirstPage; //Whether it is the first page

 var $isLastPage; //Whether it is the last page

 var $sql; //sql query statement

 function Pager($option)

 {

 global $db;

 $this->_setOptions($option);

  // Total number of items

 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;

 }

 /***

 *

  * Return the database connection of the result set

  * When the result set is relatively large, you can directly use this method to obtain the database connection, and then traverse outside the class, which has less overhead

  * If the result set is not very large, you can directly use getPageData to obtain the 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 Pear DB::limitQuery method to ensure database compatibility

 return $link;

 }

 else

 {

 return false;

 }

 }

 /***

 *

  * Return the result set in the format of a two-dimensional array

 *

 ***/

 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 that uses the pear db class to establish a database connection is omitted

 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 = "Homepage|Previous Page|";
}

 if ( $pager->isLastPage )

 {

 $turnover .= "Next page|Last page";

 }

 else

 {

  $turnover .="Next Page|< ;a href='?page=".$pager->numPages."&numItems=".$pager->numItems."'>Last Page";
}

  ?>

There are two things that need to be explained:

 This class only processes data and is not responsible for display, because I think it is a bit reluctant to put both data processing and result display into one class. When displaying, the situation and requirements are changeable. It is better to process it according to the results given by the class. A better way is to inherit a subclass of your own based on the Pager class to display different paginations. For example, displaying the user pagination list can:

 

 Class MemberPager extends Pager

 {

 function showMemberList()

 {

 global $db;

 $data = $this->getPageData();

  // Code to display results

  //......

 }

 }

  /// 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 that needs to be explained is the compatibility of different databases. The way to write a section of results in different databases is different.

 mysql: select * from table limit offset, rows

 pgsql: select * from table limit m offset n

 ……

 So when you want to get the results in the class, you need to use the limitQuery method of the pear db class.

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/371844.htmlTechArticle 1. Preface Paging display is a very common method of browsing and displaying large amounts of data, and it is one of the most commonly processed events in web programming. For web programming veterans, writing this code...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn