


Detailed explanation of PHP pagination display production_PHP tutorial
Jul 21, 2016 pm 04:08 PM
1、前言
分頁(yè)顯示是一種非常常見(jiàn)的瀏覽和顯示大量數(shù)據(jù)的方法,屬于web編程中最常處理的事件之一。對(duì)于web編程的老手來(lái)說(shuō),編寫(xiě)這種代碼實(shí)在是和呼吸一樣自然,但是對(duì)于初學(xué)者來(lái)說(shuō),常常對(duì)這個(gè)問(wèn)題摸不著頭緒,因此特地撰寫(xiě)此文對(duì)這個(gè)問(wèn)題進(jìn)行詳細(xì)的講解,力求讓看完這篇文章的朋友在看完以后對(duì)于分頁(yè)顯示的原理和實(shí)現(xiàn)方法有所了解。本文適合初學(xué)者閱讀,所有示例代碼均使用php編寫(xiě)。
2、原理
所謂分頁(yè)顯示,也就是將數(shù)據(jù)庫(kù)中的結(jié)果集人為的分成一段一段的來(lái)顯示,這里需要兩個(gè)初始的參數(shù):
每頁(yè)多少條記錄($PageSize)?
當(dāng)前是第幾頁(yè)($CurrentPageID)?
現(xiàn)在只要再給我一個(gè)結(jié)果集,我就可以顯示某段特定的結(jié)果出來(lái)。
至于其他的參數(shù),比如:上一頁(yè)($PreviousPageID)、下一頁(yè)($NextPageID)、總頁(yè)數(shù)($numPages)等等,都可以根據(jù)前邊這幾個(gè)東西得到。
以mysql數(shù)據(jù)庫(kù)為例,如果要從表內(nèi)截取某段內(nèi)容,sql語(yǔ)句可以用:select * from table limit offset, rows。看看下面一組sql語(yǔ)句,嘗試一下發(fā)現(xiàn)其中的規(guī)率。
前10條記錄:select * from table limit 0,10
第11至20條記錄:select * from table limit 10,10
第21至30條記錄:select * from table limit 20,10
……
這一組sql語(yǔ)句其實(shí)就是當(dāng)$PageSize=10的時(shí)候取表內(nèi)每一頁(yè)數(shù)據(jù)的sql語(yǔ)句,我們可以總結(jié)出這樣一個(gè)模板:
select * from table limit ($CurrentPageID - 1) * $PageSize, $PageSize
拿這個(gè)模板代入對(duì)應(yīng)的值和上邊那一組sql語(yǔ)句對(duì)照一下看看是不是那么回事。搞定了最重要的如何獲取數(shù)據(jù)的問(wèn)題以后,剩下的就僅僅是傳遞參數(shù),構(gòu)造合適的sql語(yǔ)句然后使用php從數(shù)據(jù)庫(kù)內(nèi)獲取數(shù)據(jù)并顯示了。以下我將用具體代碼加以說(shuō)明。
3、簡(jiǎn)單代碼
請(qǐng)?jiān)敿?xì)閱讀以下代碼,自己調(diào)試運(yùn)行一次,最好把它修改一次,加上自己的功能,比如搜索等等。
// 建立數(shù)據(jù)庫(kù)連接
$link = mysql_connect("localhost", "mysql_user", "mysql_password")
or die("Could not connect: " . mysql_error());
// 獲取當(dāng)前頁(yè)數(shù)
if( isset($_GET['page']) ){
$page = intval( $_GET['page'] );
}
else{
$page = 1;
}
// 每頁(yè)數(shù)量
$PageSize = 10;
// 獲取總數(shù)據(jù)量
$sql = "select count(*) as amount from table";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
$amount = $row['amount'];
// 記算總共有多少頁(yè)
if( $amount ){
if( $amount < $page_size ){ $page_count = 1; } //如果總數(shù)據(jù)量小于$PageSize,那么只有一頁(yè)
if( $amount % $page_size ){ //取總數(shù)據(jù)量除以每頁(yè)數(shù)的余數(shù)
$page_count = (int)($amount / $page_size) + 1; //如果有余數(shù),則頁(yè)數(shù)等于總數(shù)據(jù)量除以每頁(yè)數(shù)的結(jié)果取整再加一
}else{
$page_count = $amount / $page_size; //如果沒(méi)有余數(shù),則頁(yè)數(shù)等于總數(shù)據(jù)量除以每頁(yè)數(shù)的結(jié)果
}
}
else{
$page_count = 0;
}
// 翻頁(yè)鏈接
$page_string = '';
if( $page == 1 ){
$page_string .= '第一頁(yè)|上一頁(yè)|';
}
else{
$page_string .= '第一頁(yè)|上一頁(yè)|';
}
if( ($page == $page_count) || ($page_count == 0) ){
?? $page_string .= '下一頁(yè)|尾頁(yè)';
}
else{
?? $page_string .= '下一頁(yè)|尾頁(yè)';
}
// 獲取數(shù)據(jù),以二維數(shù)組格式返回結(jié)果
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();
}
// 沒(méi)有包含顯示結(jié)果的代碼,那不在討論范圍,只要用foreach就可以很簡(jiǎn)單的用得到的二維數(shù)組來(lái)顯示結(jié)果
?>
4、OO風(fēng)格代碼
以下代碼中的數(shù)據(jù)庫(kù)連接是使用的pear db類(lèi)進(jìn)行處理
// 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; Pages
var $numPages; //Total number of pages
var $numItems; //Total number of records
var $isFirstPage; one Page
var $sql;
??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????>?????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????> If ( $this->numItems < $this->PageSize ){ $this->numPages = 1; }
If ( $this->numItems % $this->PageSize )
??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????this->numPages = $this->numItems / $this->PageSize;
}
}
else
?? > }
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:
?????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????? through >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方法保證數(shù)據(jù)庫(kù)兼容性
?????????? 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 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:
Class MemberPager extends Pager
{
function showMemberList()
global $db;
$data = $this-> getPageData();
// Code to display the results???????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????. 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 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, I’ll take credit when I’m done. I hope you don’t feel like it’s a waste of time if you take the time to read these words.

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHPhasthreecommentstyles://,#forsingle-lineand/.../formulti-line.Usecommentstoexplainwhycodeexists,notwhatitdoes.MarkTODO/FIXMEitemsanddisablecodetemporarilyduringdebugging.Avoidover-commentingsimplelogic.Writeconcise,grammaticallycorrectcommentsandu

The key steps to install PHP on Windows include: 1. Download the appropriate PHP version and decompress it. It is recommended to use ThreadSafe version with Apache or NonThreadSafe version with Nginx; 2. Configure the php.ini file and rename php.ini-development or php.ini-production to php.ini; 3. Add the PHP path to the system environment variable Path for command line use; 4. Test whether PHP is installed successfully, execute php-v through the command line and run the built-in server to test the parsing capabilities; 5. If you use Apache, you need to configure P in httpd.conf

PHPisaserver-sidescriptinglanguageusedforwebdevelopment,especiallyfordynamicwebsitesandCMSplatformslikeWordPress.Itrunsontheserver,processesdata,interactswithdatabases,andsendsHTMLtobrowsers.Commonusesincludeuserauthentication,e-commerceplatforms,for

TohandlefileoperationsinPHP,useappropriatefunctionsandmodes.1.Toreadafile,usefile_get_contents()forsmallfilesorfgets()inaloopforline-by-lineprocessing.2.Towritetoafile,usefile_put_contents()forsimplewritesorappendingwiththeFILE_APPENDflag,orfwrite()w

How to start writing your first PHP script? First, set up the local development environment, install XAMPP/MAMP/LAMP, and use a text editor to understand the server's running principle. Secondly, create a file called hello.php, enter the basic code and run the test. Third, learn to use PHP and HTML to achieve dynamic content output. Finally, pay attention to common errors such as missing semicolons, citation issues, and file extension errors, and enable error reports for debugging.

The basic syntax of PHP includes four key points: 1. The PHP tag must be ended, and the use of complete tags is recommended; 2. Echo and print are commonly used for output content, among which echo supports multiple parameters and is more efficient; 3. The annotation methods include //, # and //, to improve code readability; 4. Each statement must end with a semicolon, and spaces and line breaks do not affect execution but affect readability. Mastering these basic rules can help write clear and stable PHP code.

The steps to install PHP8 on Ubuntu are: 1. Update the software package list; 2. Install PHP8 and basic components; 3. Check the version to confirm that the installation is successful; 4. Install additional modules as needed. Windows users can download and decompress the ZIP package, then modify the configuration file, enable extensions, and add the path to environment variables. macOS users recommend using Homebrew to install, and perform steps such as adding tap, installing PHP8, setting the default version and verifying the version. Although the installation methods are different under different systems, the process is clear, so you can choose the right method according to the purpose.

The key to writing Python's ifelse statements is to understand the logical structure and details. 1. The infrastructure is to execute a piece of code if conditions are established, otherwise the else part is executed, else is optional; 2. Multi-condition judgment is implemented with elif, and it is executed sequentially and stopped once it is met; 3. Nested if is used for further subdivision judgment, it is recommended not to exceed two layers; 4. A ternary expression can be used to replace simple ifelse in a simple scenario. Only by paying attention to indentation, conditional order and logical integrity can we write clear and stable judgment codes.
