国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home Backend Development PHP Tutorial Detailed explanation of PHP pagination display production_PHP tutorial

Detailed explanation of PHP pagination display production_PHP tutorial

Jul 21, 2016 pm 04:08 PM
php Pagination make Preface and belong data method yes show Browse of explain detailed No

1、前言

分頁顯示是一種非常常見的瀏覽和顯示大量數(shù)據(jù)的方法,屬于web編程中最常處理的事件之一。對(duì)于web編程的老手來說,編寫這種代碼實(shí)在是和呼吸一樣自然,但是對(duì)于初學(xué)者來說,常常對(duì)這個(gè)問題摸不著頭緒,因此特地撰寫此文對(duì)這個(gè)問題進(jìn)行詳細(xì)的講解,力求讓看完這篇文章的朋友在看完以后對(duì)于分頁顯示的原理和實(shí)現(xiàn)方法有所了解。本文適合初學(xué)者閱讀,所有示例代碼均使用php編寫。

2、原理

所謂分頁顯示,也就是將數(shù)據(jù)庫中的結(jié)果集人為的分成一段一段的來顯示,這里需要兩個(gè)初始的參數(shù):

每頁多少條記錄($PageSize)?
當(dāng)前是第幾頁($CurrentPageID)?

現(xiàn)在只要再給我一個(gè)結(jié)果集,我就可以顯示某段特定的結(jié)果出來。
至于其他的參數(shù),比如:上一頁($PreviousPageID)、下一頁($NextPageID)、總頁數(shù)($numPages)等等,都可以根據(jù)前邊這幾個(gè)東西得到。
以mysql數(shù)據(jù)庫為例,如果要從表內(nèi)截取某段內(nèi)容,sql語句可以用:select * from table limit offset, rows??纯聪旅嬉唤Msql語句,嘗試一下發(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語句其實(shí)就是當(dāng)$PageSize=10的時(shí)候取表內(nèi)每一頁數(shù)據(jù)的sql語句,我們可以總結(jié)出這樣一個(gè)模板:

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

拿這個(gè)模板代入對(duì)應(yīng)的值和上邊那一組sql語句對(duì)照一下看看是不是那么回事。搞定了最重要的如何獲取數(shù)據(jù)的問題以后,剩下的就僅僅是傳遞參數(shù),構(gòu)造合適的sql語句然后使用php從數(shù)據(jù)庫內(nèi)獲取數(shù)據(jù)并顯示了。以下我將用具體代碼加以說明。

3、簡單代碼
請?jiān)敿?xì)閱讀以下代碼,自己調(diào)試運(yùn)行一次,最好把它修改一次,加上自己的功能,比如搜索等等。

// 建立數(shù)據(jù)庫連接
$link = mysql_connect("localhost", "mysql_user", "mysql_password")
or die("Could not connect: " . mysql_error());
// 獲取當(dāng)前頁數(shù)
if( isset($_GET['page']) ){
$page = intval( $_GET['page'] );
}
else{
$page = 1;
}
// 每頁數(shù)量
$PageSize = 10;
// 獲取總數(shù)據(jù)量
$sql = "select count(*) as amount from table";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
$amount = $row['amount'];
// 記算總共有多少頁
if( $amount ){
if( $amount < $page_size ){ $page_count = 1; } //如果總數(shù)據(jù)量小于$PageSize,那么只有一頁
if( $amount % $page_size ){ //取總數(shù)據(jù)量除以每頁數(shù)的余數(shù)
$page_count = (int)($amount / $page_size) + 1; //如果有余數(shù),則頁數(shù)等于總數(shù)據(jù)量除以每頁數(shù)的結(jié)果取整再加一
}else{
$page_count = $amount / $page_size; //如果沒有余數(shù),則頁數(shù)等于總數(shù)據(jù)量除以每頁數(shù)的結(jié)果
}
}
else{
$page_count = 0;
}

// 翻頁鏈接
$page_string = '';
if( $page == 1 ){
$page_string .= '第一頁|上一頁|';
}
else{
$page_string .= '第一頁|上一頁|';
}
if( ($page == $page_count) || ($page_count == 0) ){
?? $page_string .= '下一頁|尾頁';
}
else{
?? $page_string .= '下一頁|尾頁';
}
// 獲取數(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();
}
// 沒有包含顯示結(jié)果的代碼,那不在討論范圍,只要用foreach就可以很簡單的用得到的二維數(shù)組來顯示結(jié)果
?>

4、OO風(fēng)格代碼
以下代碼中的數(shù)據(jù)庫連接是使用的pear db類進(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ù)庫兼容性

?????????? 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.



www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/314945.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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

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)

Hot Topics

PHP Tutorial
1488
72
PHP calls AI intelligent voice assistant PHP voice interaction system construction PHP calls AI intelligent voice assistant PHP voice interaction system construction Jul 25, 2025 pm 08:45 PM

User voice input is captured and sent to the PHP backend through the MediaRecorder API of the front-end JavaScript; 2. PHP saves the audio as a temporary file and calls STTAPI (such as Google or Baidu voice recognition) to convert it into text; 3. PHP sends the text to an AI service (such as OpenAIGPT) to obtain intelligent reply; 4. PHP then calls TTSAPI (such as Baidu or Google voice synthesis) to convert the reply to a voice file; 5. PHP streams the voice file back to the front-end to play, completing interaction. The entire process is dominated by PHP to ensure seamless connection between all links.

How to use PHP to build social sharing functions PHP sharing interface integration practice How to use PHP to build social sharing functions PHP sharing interface integration practice Jul 25, 2025 pm 08:51 PM

The core method of building social sharing functions in PHP is to dynamically generate sharing links that meet the requirements of each platform. 1. First get the current page or specified URL and article information; 2. Use urlencode to encode the parameters; 3. Splice and generate sharing links according to the protocols of each platform; 4. Display links on the front end for users to click and share; 5. Dynamically generate OG tags on the page to optimize sharing content display; 6. Be sure to escape user input to prevent XSS attacks. This method does not require complex authentication, has low maintenance costs, and is suitable for most content sharing needs.

How to use PHP combined with AI to achieve text error correction PHP syntax detection and optimization How to use PHP combined with AI to achieve text error correction PHP syntax detection and optimization Jul 25, 2025 pm 08:57 PM

To realize text error correction and syntax optimization with AI, you need to follow the following steps: 1. Select a suitable AI model or API, such as Baidu, Tencent API or open source NLP library; 2. Call the API through PHP's curl or Guzzle and process the return results; 3. Display error correction information in the application and allow users to choose whether to adopt it; 4. Use php-l and PHP_CodeSniffer for syntax detection and code optimization; 5. Continuously collect feedback and update the model or rules to improve the effect. When choosing AIAPI, focus on evaluating accuracy, response speed, price and support for PHP. Code optimization should follow PSR specifications, use cache reasonably, avoid circular queries, review code regularly, and use X

PHP creates a blog comment system to monetize PHP comment review and anti-brush strategy PHP creates a blog comment system to monetize PHP comment review and anti-brush strategy Jul 25, 2025 pm 08:27 PM

1. Maximizing the commercial value of the comment system requires combining native advertising precise delivery, user paid value-added services (such as uploading pictures, top-up comments), influence incentive mechanism based on comment quality, and compliance anonymous data insight monetization; 2. The audit strategy should adopt a combination of pre-audit dynamic keyword filtering and user reporting mechanisms, supplemented by comment quality rating to achieve content hierarchical exposure; 3. Anti-brushing requires the construction of multi-layer defense: reCAPTCHAv3 sensorless verification, Honeypot honeypot field recognition robot, IP and timestamp frequency limit prevents watering, and content pattern recognition marks suspicious comments, and continuously iterate to deal with attacks.

How to use PHP to combine AI to generate image. PHP automatically generates art works How to use PHP to combine AI to generate image. PHP automatically generates art works Jul 25, 2025 pm 07:21 PM

PHP does not directly perform AI image processing, but integrates through APIs, because it is good at web development rather than computing-intensive tasks. API integration can achieve professional division of labor, reduce costs, and improve efficiency; 2. Integrating key technologies include using Guzzle or cURL to send HTTP requests, JSON data encoding and decoding, API key security authentication, asynchronous queue processing time-consuming tasks, robust error handling and retry mechanism, image storage and display; 3. Common challenges include API cost out of control, uncontrollable generation results, poor user experience, security risks and difficult data management. The response strategies are setting user quotas and caches, providing propt guidance and multi-picture selection, asynchronous notifications and progress prompts, key environment variable storage and content audit, and cloud storage.

PHP realizes commodity inventory management and monetization PHP inventory synchronization and alarm mechanism PHP realizes commodity inventory management and monetization PHP inventory synchronization and alarm mechanism Jul 25, 2025 pm 08:30 PM

PHP ensures inventory deduction atomicity through database transactions and FORUPDATE row locks to prevent high concurrent overselling; 2. Multi-platform inventory consistency depends on centralized management and event-driven synchronization, combining API/Webhook notifications and message queues to ensure reliable data transmission; 3. The alarm mechanism should set low inventory, zero/negative inventory, unsalable sales, replenishment cycles and abnormal fluctuations strategies in different scenarios, and select DingTalk, SMS or Email Responsible Persons according to the urgency, and the alarm information must be complete and clear to achieve business adaptation and rapid response.

Beyond the LAMP Stack: PHP's Role in Modern Enterprise Architecture Beyond the LAMP Stack: PHP's Role in Modern Enterprise Architecture Jul 27, 2025 am 04:31 AM

PHPisstillrelevantinmodernenterpriseenvironments.1.ModernPHP(7.xand8.x)offersperformancegains,stricttyping,JITcompilation,andmodernsyntax,makingitsuitableforlarge-scaleapplications.2.PHPintegrateseffectivelyinhybridarchitectures,servingasanAPIgateway

PHP integrated AI speech recognition and translator PHP meeting record automatic generation solution PHP integrated AI speech recognition and translator PHP meeting record automatic generation solution Jul 25, 2025 pm 07:06 PM

Select the appropriate AI voice recognition service and integrate PHPSDK; 2. Use PHP to call ffmpeg to convert recordings into API-required formats (such as wav); 3. Upload files to cloud storage and call API asynchronous recognition; 4. Analyze JSON results and organize text using NLP technology; 5. Generate Word or Markdown documents to complete the automation of meeting records. The entire process needs to ensure data encryption, access control and compliance to ensure privacy and security.

See all articles