Home Backend Development PHP Tutorial Detailed explanation of PHP paging (with examples)_PHP tutorial

Detailed explanation of PHP paging (with examples)_PHP tutorial

Jul 13, 2016 am 10:25 AM
php pagination

1. Introduction
Paging display is a very common method of browsing and displaying large amounts of data, and 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 per page Records($PageSize)?
What page is the current page ($CurrentPageID)?
Now just give me another result set and 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.
Take 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
The 11th to 20th records: select * from table limit 10,10
The 21st to 30th records: select * from table limit 20 ,10
...
This set of sql statements is actually the sql statement to fetch data from each page of 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 value 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.

Copy code The code is as follows:

//Establish a 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;
}
// Number of pages per page
$PageSize = 10;
// Get total data volume
$sql = "select count(*) as amount from table";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
$amount = $row['amount'] ;
// Calculate the total number of pages
if( $amount ){
if( $amount < $page_size ){ $page_count = 1; }                                                                    Then there is only one page
if( $amount % $page_size ){ 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 The result equal to the total amount of data divided by the number of pages
}
}
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|';
}
if( ($page == $page_count) || ($page_count == 0) ){
$page_string .= ' Next page|Last page';
}
else{
$page_string .= 'Next page< /a>|Last 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( ; 🎜>

4. OO style code

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


Copy code
The code is as follows:

// FileName: Pager.class.php
// Paging class, this class is only used to process data structures and is not responsible for processing display work
Class Pager
{
var $PageSize; //The number of each page
var $CurrentPageID; //The current page number
var $NextPageID; //Next page
var $PreviousPageID; / /Previous VAR $ numpaages; // Total page
var $ Numitems; // Total records
VAR $ isfirstPage; // Whether the first page
var $ isLastPage; // Is the last page
var $sql; //sql query statement

function Pager($option)
{
global $db; option);
                                                                                                                                        ; > {
IF ($ this-& gt; numitems & lt; $ this- & gt; pagesize) {$ this- & gt; numpaages = 1;}
IF ($ this-& gt; numitems % -& gt; PageSize )
                                                                                                                                                                                                                             🎜>                                                   {
            $this->numPages = $this->numItems / $this->PageSize;                                                  $this->numPages = 0 ;
}

switch ( $this->CurrentPageID )
{
numPages == 1:
$this->isFirst Page = 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, so the overhead is smaller
* 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 is also called to obtain the results
*
***/

   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);   //使用Pear DB::limitQuery方法保证数据库兼容性

           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) } 🎜>?>
// FileName: test_pager.php
// This is a simple sample code. The code for using 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|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, to display the user pagination list:




Copy code
The code is as follows:

Class MemberPager extends Pager
{ function showMemberList() { global $db;
$data = $this->getPageData();
// Code to display 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 point that needs to be explained is the compatibility of different databases. The way to intercept a result in different databases is different.
mysql: select * from table limit offset, rows
pgsql: select * from table limit m offset n
......
So you need to use pear when you want to get the result in the class The limitQuery method of the db class.

ok, finished writing.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/824950.htmlTechArticle1. Preface Pagination display is a very common method of browsing and displaying large amounts of data, which is the most common method in web programming. One of the commonly handled events. For web programming veterans, writing this code...
Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Framework Security Features: Protecting against vulnerabilities. Framework Security Features: Protecting against vulnerabilities. Mar 28, 2025 pm 05:11 PM

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

Customizing/Extending Frameworks: How to add custom functionality. Customizing/Extending Frameworks: How to add custom functionality. Mar 28, 2025 pm 05:12 PM

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

See all articles