Home Backend Development PHP Tutorial PHP paging Detailed explanation of PHP paging display production

PHP paging Detailed explanation of PHP paging display production

Mar 16, 2017 pm 03:49 PM
php pagination

1. Introduction

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 artificially dividing the result set in the database into sections 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.

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 for fetching 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 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.

<?php 
// 建立数据库连接 
$link = mysql_connect("localhost", "mysql_user", "mysql_password") 
or die("Could not connect: " . mysql_error()); 
// 获取当前页数 
if( isset($_GET[&#39;page&#39;]) ){ 
$page = intval( $_GET[&#39;page&#39;] ); 
} 
else{ 
$page = 1; 
} 
// 每页数量 
$PageSize = 10; 
// 获取总数据量 
$sql = "select count(*) as amount from table"; 
$result = mysql_query($sql); 
$row = mysql_fetch_row($result); 
$amount = $row[&#39;amount&#39;]; 
// 记算总共有多少页 
if( $amount ){ 
if( $amount < $page_size ){ $page_count = 1; } //如果总数据量小于$PageSize,那么只有一页 
if( $amount % $page_size ){ //取总数据量除以每页数的余数 
$page_count = (int)($amount / $page_size) + 1; //如果有余数,则页数等于总数据量除以每页数的结果取整再加一 
}else{ 
$page_count = $amount / $page_size; //如果没有余数,则页数等于总数据量除以每页数的结果 
} 
} 
else{ 
$page_count = 0; 
} 
// 翻页链接 
$page_string = &#39;&#39;; 
if( $page == 1 ){ 
$page_string .= &#39;第一页|上一页|&#39;; 
} 
else{ 
$page_string .= &#39;<a href=?page=1>第一页</a>|<a href=?page=&#39;.($page-1).&#39;>上一页</a>|&#39;; 
} 
if( ($page == $page_count) || ($page_count == 0) ){ 
$page_string .= &#39;下一页|尾页&#39;; 
} 
else{ 
$page_string .= &#39;<a href=?page=&#39;.($page+1).&#39;>下一页</a>|<a href=?page=&#39;.$page_count.&#39;>尾页</a>&#39;; 
} 
// 获取数据,以二维数组格式返回结果 
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(); 
} 
// 没有包含显示结果的代码,那不在讨论范围,只要用foreach就可以很简单的用得到的二维数组来显示结果 
?>
Copy after login

4. OO style code

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

<?php 
// FileName: Pager.class.php 
// 分页类,这个类仅仅用于处理数据结构,不负责处理显示的工作 
Class Pager 
{ 
var $PageSize; //每页的数量 
var $CurrentPageID; //当前的页数 
var $NextPageID; //下一页 
var $PreviousPageID; //上一页 
var $numPages; //总页数 
var $numItems; //总记录数 
var $isFirstPage; //是否第一页 
var $isLastPage; //是否最后一页 
var $sql; //sql查询语句 
function Pager($option) 
{ 
global $db; 
$this->_setOptions($option); 
// 总条数 
if ( !isset($this->numItems) ) 
{ 
$res = $db->query($this->sql); 
$this->numItems = $res->numRows(); 
} 
// 总页数 
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; 
} 
/*** 
* 
* 返回结果集的数据库连接 
* 在结果集比较大的时候可以直接使用这个方法获得数据库连接,然后在类之外遍历,这样开销较小 
* 如果结果集不是很大,可以直接使用getPageData的方式获取二维数组格式的结果 
* getPageData方法也是调用本方法来获取结果的 
* 
***/ 
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; 
} 
} 
/*** 
* 
* 以二维数组的格式返回结果集 
* 
***/ 
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( 
&#39;PageSize&#39;, 
&#39;CurrentPageID&#39;, 
&#39;sql&#39;, 
&#39;numItems&#39; 
); 
foreach ( $option as $key => $value ) 
{ 
if ( in_array($key, $allow_options) && ($value != null) ) 
{ 
$this->$key = $value; 
} 
} 
return true; 
} 
} 
?> 
<?php 
// FileName: test_pager.php 
// 这是一段简单的示例代码,前边省略了使用pear db类建立数据库连接的代码 
require "Pager.class.php"; 
if ( isset($_GET[&#39;page&#39;]) ) 
{ 
$page = (int)$_GET[&#39;page&#39;]; 
} 
else 
{ 
$page = 1; 
} 
$sql = "select * from table order by id"; 
$pager_option = array( 
"sql" => $sql, 
"PageSize" => 10, 
"CurrentPageID" => $page 
); 
if ( isset($_GET[&#39;numItems&#39;]) ) 
{ 
$pager_option[&#39;numItems&#39;] = (int)$_GET[&#39;numItems&#39;]; 
} 
$pager = @new Pager($pager_option); 
$data = $pager->getPageData(); 
if ( $pager->isFirstPage ) 
{ 
$turnover = "首页|上一页|"; 
} 
else 
{ 
$turnover = "<a href=&#39;?page=1&numItems=".$pager->numItems."&#39;>首页</a>|<a href=&#39;?page=".$pager->PreviousPageID."&numItems=".$pager->numItems."&#39;>上一页</a>|"; 
} 
if ( $pager->isLastPage ) 
{ 
$turnover .= "下一页|尾页"; 
} 
else 
{ 
$turnover .= "<a href=&#39;?page=".$pager->NextPageID."&numItems=".$pager->numItems."&#39;>下一页</a>|<a href=&#39;?page=".$pager->numPages."&numItems=".$pager->numItems."&#39;>尾页</a>"; 
} 
?>
Copy after login

There are two things that need to be explained:

This class only processes data and is not responsible for processing 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 handle 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 be:

<?php 
Class MemberPager extends Pager 
{ 
function showMemberList() 
{ 
global $db; 
$data = $this->getPageData(); 
// 显示结果的代码 
// ...... 
} 
} 
/// 调用 
if ( isset($_GET[&#39;page&#39;]) ) 
{ 
$page = (int)$_GET[&#39;page&#39;]; 
} 
else 
{ 
$page = 1; 
} 
$sql = "select * from members order by id"; 
$pager_option = array( 
"sql" => $sql, 
"PageSize" => 10, 
"CurrentPageID" => $page 
); 
if ( isset($_GET[&#39;numItems&#39;]) ) 
{ 
$pager_option[&#39;numItems&#39;] = (int)$_GET[&#39;numItems&#39;]; 
} 
$pager = @new MemberPager($pager_option); 
$pager->showMemberList(); 
?>
Copy after login

The second thing 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 when you want to get the results in the class, you need to use the limitQuery of the pear db class method.

ok, I’ll take credit when I’m done. I hope you don’t feel it’s a waste of time if you take the time to read these words.

The above introduces PHP paging and a detailed explanation of PHP paging display production, including PHP paging content. I hope it will be helpful to friends who are interested in PHP tutorials.

Related articles:

Use PHP to implement simple paging class and its detailed usage

php paging class code

php Detailed explanation of paging principle

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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
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)

11 Best PHP URL Shortener Scripts (Free and Premium) 11 Best PHP URL Shortener Scripts (Free and Premium) Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Introduction to the Instagram API Introduction to the Instagram API Mar 02, 2025 am 09:32 AM

Following its high-profile acquisition by Facebook in 2012, Instagram adopted two sets of APIs for third-party use. These are the Instagram Graph API and the Instagram Basic Display API.As a developer building an app that requires information from a

Working with Flash Session Data in Laravel Working with Flash Session Data in Laravel Mar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Build a React App With a Laravel Back End: Part 2, React Build a React App With a Laravel Back End: Part 2, React Mar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Simplified HTTP Response Mocking in Laravel Tests Simplified HTTP Response Mocking in Laravel Tests Mar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

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

Announcement of 2025 PHP Situation Survey Announcement of 2025 PHP Situation Survey Mar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

See all articles