Maison php教程 php手册 PHP分页详细讲解

PHP分页详细讲解

Jun 06, 2016 pm 07:47 PM
php 分页 Préface 显示 讲解 详细

1、前言 分页显示是一种非常常见的浏览和显示大量数据的方法,属于web编程中最常处理的事件之一。对于web编程的老手来说,编写这种代码实在是和呼吸一样自然,但是对于初学者来说,常常对这个问题摸不着头绪,因此特地撰写此文对这个问题进行详细的讲解,力

1、前言
分页显示是一种非常常见的浏览和显示大量数据的方法,属于web编程中最常处理的事件之一。对于web编程的老手来说,编写这种代码实在是和呼吸一样自然,但是对于初学者来说,常常对这个问题摸不着头绪,因此特地撰写此文对这个问题进行详细的讲解,力求让看完这篇文章的朋友在看完以后对于分页显示的原理和实现方法有所了解。本文适合初学者阅读,所有示例代码均使用php编写。
2、原理
所谓分页显示,也就是将数据库中的结果集人为的分成一段一段的来显示,这里需要两个初始的参数:
每页多少条记录($PageSize)?
当前是第几页($CurrentPageID)?
现在只要再给我一个结果集,我就可以显示某段特定的结果出来。

以MySQL数据库为例,如果要从表内截取某段内容,sql语句可以用:select * from table limit offset, rows。看看下面一组sql语句,尝试一下发现其中的规率。
前10条记录:select * from table limit 0,10
第11至20条记录:select * from table limit 10,10
第21至30条记录:select * from table limit 20,10
……
这一组sql语句其实就是当$PageSize=10的时候取表内每一页数据的sql语句,我们可以总结出这样一个模板:
select * from table limit ($CurrentPageID - 1) * $PageSize, $PageSize
拿这个模板代入对应的值和上边那一组sql语句对照一下看看是不是那么回事。搞定了最重要的如何获取数据的问题以后,剩下的就仅仅是传递参数,构造合适的sql语句然后使用php从数据库内获取数据并显示了。以下我将用具体代码加以说明。
3、简单代码
请详细阅读以下代码,自己调试运行一次,最好把它修改一次,加上自己的功能,比如搜索等等。

<span>php
</span><span>//</span><span> 建立数据库连接</span>
<span>$link</span> = <span>mysql_connect</span>("localhost", "mysql_user", "mysql_passWord"<span>) 
      or </span><span>die</span>("Could not connect: " . <span>mysql_error</span><span>()); 
</span><span>//</span><span> 获取当前页数</span>
<span>if</span>( <span>isset</span>(<span>$_GET</span>['page'<span>]) ){
   </span><span>$page</span> = <span>intval</span>( <span>$_GET</span>['page'<span>] );
}
</span><span>else</span><span>{
   </span><span>$page</span> = 1<span>;
} 
</span><span>//</span><span> 每页数量</span>
<span>$PageSize</span> = 10<span>; 
</span><span>//</span><span> 获取总数据量</span>
<span>$sql</span> = "select count(*) as amount from table"<span>;
</span><span>$result</span> = <span>mysql_query</span>(<span>$sql</span><span>);
</span><span>$row</span> = <span>mysql_fetch_row</span>(<span>$result</span><span>);
</span><span>$amount</span> = <span>$row</span>['amount'<span>]; 
</span><span>//</span><span> 记算总共有多少页</span>
<span>if</span>( <span>$amount</span><span> ){
   </span><span>if</span>( <span>$amount</span> $page_size ){ <span>$page_count</span> = 1; }               <span>//</span><span>如果总数据量小于$PageSize,那么只有一页</span>
   <span>if</span>( <span>$amount</span> % <span>$page_size</span> ){                                  <span>//</span><span>取总数据量除以每页数的余数</span>
       <span>$page_count</span> = (int)(<span>$amount</span> / <span>$page_size</span>) + 1;           <span>//</span><span>如果有余数,则页数等于总数据量除以每页数的结果取整再加一</span>
   }<span>else</span><span>{
       </span><span>$page_count</span> = <span>$amount</span> / <span>$page_size</span>;                      <span>//</span><span>如果没有余数,则页数等于总数据量除以每页数的结果</span>
<span>   }
}
</span><span>else</span><span>{
   </span><span>$page_count</span> = 0<span>;
}

</span><span>//</span><span> 翻页链接</span>
<span>$page_string</span> = ''<span>;
</span><span>if</span>( <span>$page</span> == 1<span> ){
   </span><span>$page_string</span><span>;
}
</span><span>else</span><span>{
   </span><span>$page_string</span> .= '<a href="?page=1">第一页</a>|<a href="?page='.(<span">$page<span>;
} 
</span><span>if</span>( (<span>$page</span> == <span>$page_count</span>) || (<span>$page_count</span> == 0<span>) ){
   </span><span>$page_string</span><span>;
}
</span><span>else</span><span>{
   </span><span>$page_string</span> .= '</a><a href="?page='.(<span">$page<span>$page_count</span>.'>尾页</a>'<span>;
}
</span><span>//</span><span> 获取数据,以二维数组格式返回结果</span>
<span>if</span>( <span>$amount</span><span> ){
   </span><span>$sql</span> = "select * from table order by id desc limit ". (<span>$page</span>-1)*<span>$page_size</span> .", <span>$page_size</span>"<span>;
   </span><span>$result</span> = <span>mysql_query</span>(<span>$sql</span><span>);

   </span><span>while</span> ( <span>$row</span> = <span>mysql_fetch_row</span>(<span>$result</span><span>) ){
       </span><span>$rowset</span>[] = <span>$row</span><span>;
   }
}</span><span>else</span><span>{
   </span><span>$rowset</span> = <span>array</span><span>();
}
</span><span>//</span><span> 没有包含显示结果的代码,那不在讨论范围,只要用foreach就可以很简单的用得到的二维数组来显示结果</span>
?>
Copier après la connexion

 4、OO风格代码
以下代码中的数据库连接是使用的pear db类进行处理

<span>php
</span><span>//</span><span> FileName: Pager.class.php
// 分页类,这个类仅仅用于处理数据结构,不负责处理显示的工作</span>
<span>Class</span><span> Pager
{
   </span><span>var</span> <span>$PageSize</span>;             <span>//</span><span>每页的数量</span>
   <span>var</span> <span>$CurrentPageID</span>;        <span>//</span><span>当前的页数</span>
   <span>var</span> <span>$NextPageID</span>;           <span>//</span>
   <span>var</span> <span>$PreviousPageID</span>;       <span>//</span>
   <span>var</span> <span>$numPages</span>;             <span>//</span><span>总页数</span>
   <span>var</span> <span>$numItems</span>;             <span>//</span><span>总记录数</span>
   <span>var</span> <span>$isFirstPage</span>;          <span>//</span><span>是否第一页</span>
   <span>var</span> <span>$isLastPage</span>;           <span>//</span><span>是否最后一页</span>
   <span>var</span> <span>$sql</span>;                  <span>//</span><span>sql查询语句</span>

  <span>function</span> Pager(<span>$option</span><span>)
   {
       </span><span>global</span> <span>$db</span><span>;
       </span><span>$this</span>->_setOptions(<span>$option</span><span>);
       </span><span>//</span><span> 总条数</span>
       <span>if</span> ( !<span>isset</span>(<span>$this</span>-><span>numItems) )
       {
           </span><span>$res</span> = <span>$db</span>->query(<span>$this</span>-><span>sql);
           </span><span>$this</span>->numItems = <span>$res</span>-><span>numRows();
       }
       </span><span>//</span><span> 总页数</span>
       <span>if</span> ( <span>$this</span>->numItems > 0<span> )
       {
           </span><span>if</span> ( <span>$this</span>->numItems $this->PageSize ){ <span>$this</span>->numPages = 1<span>; }
           </span><span>if</span> ( <span>$this</span>->numItems % <span>$this</span>-><span>PageSize )
           {
               </span><span>$this</span>->numPages= (int)(<span>$this</span>->numItems / <span>$this</span>->PageSize) + 1<span>;
           }
           </span><span>else</span><span>
           {
               </span><span>$this</span>->numPages = <span>$this</span>->numItems / <span>$this</span>-><span>PageSize;
           }
       }
       </span><span>else</span><span>
       {
           </span><span>$this</span>->numPages = 0<span>;
       }

       </span><span>switch</span> ( <span>$this</span>-><span>CurrentPageID )
       {
           </span><span>case</span> <span>$this</span>->numPages == 1:
               <span>$this</span>->isFirstPage = <span>true</span><span>;
               </span><span>$this</span>->isLastPage = <span>true</span><span>;
               </span><span>break</span><span>;
           </span><span>case</span> 1:
               <span>$this</span>->isFirstPage = <span>true</span><span>;
               </span><span>$this</span>->isLastPage = <span>false</span><span>;
               </span><span>break</span><span>;
           </span><span>case</span> <span>$this</span>->numPages:
               <span>$this</span>->isFirstPage = <span>false</span><span>;
               </span><span>$this</span>->isLastPage = <span>true</span><span>;
               </span><span>break</span><span>;
           </span><span>default</span>:
               <span>$this</span>->isFirstPage = <span>false</span><span>;
               </span><span>$this</span>->isLastPage = <span>false</span><span>;
       }

       </span><span>if</span> ( <span>$this</span>->numPages > 1<span> )
       {
           </span><span>if</span> ( !<span>$this</span>->isLastPage ) { <span>$this</span>->NextPageID = <span>$this</span>->CurrentPageID + 1<span>; }
           </span><span>if</span> ( !<span>$this</span>->isFirstPage ) { <span>$this</span>->PreviousPageID = <span>$this</span>->CurrentPageID - 1<span>; }
       }

       </span><span>return</span> <span>true</span><span>;
   }

   </span><span>/*</span><span>**
    *
    * 返回结果集的数据库连接
    * 在结果集比较大的时候可以直接使用这个方法获得数据库连接,然后在类之外遍历,这样开销较小
    * 如果结果集不是很大,可以直接使用getPageData的方式获取二维数组格式的结果
    * getPageData方法也是调用本方法来获取结果的
    *
    **</span><span>*/</span>

   <span>function</span><span> getDataLink()
   {
       </span><span>if</span> ( <span>$this</span>-><span>numItems )
       {
           </span><span>global</span> <span>$db</span><span>;

           </span><span>$PageID</span> = <span>$this</span>-><span>CurrentPageID;

           </span><span>$from</span> = (<span>$PageID</span> - 1)*<span>$this</span>-><span>PageSize;
           </span><span>$count</span> = <span>$this</span>-><span>PageSize;
           </span><span>$link</span> = <span>$db</span>->limitQuery(<span>$this</span>->sql, <span>$from</span>, <span>$count</span>);   <span>//</span><span>使用Pear DB::limitQuery方法保证数据库兼容性</span>

           <span>return</span> <span>$link</span><span>;
       }
       </span><span>else</span><span>
       {
           </span><span>return</span> <span>false</span><span>;
       }
   }

   </span><span>/*</span><span>**
    *
    * 以二维数组的格式返回结果集
    *
    **</span><span>*/</span>

   <span>function</span><span> getPageData()
   {
       </span><span>if</span> ( <span>$this</span>-><span>numItems )
       {
           </span><span>if</span> ( <span>$res</span> = <span>$this</span>-><span>getDataLink() )
           {       
               </span><span>if</span> ( <span>$res</span>-><span>numRows() )
               {
                   </span><span>while</span> ( <span>$row</span> = <span>$res</span>-><span>fetchRow() )
                   {
                       </span><span>$result</span>[] = <span>$row</span><span>;
                   }
               }
               </span><span>else</span><span>
               {
                   </span><span>$result</span> = <span>array</span><span>();
               }

               </span><span>return</span> <span>$result</span><span>;
           }
           </span><span>else</span><span>
           {
               </span><span>return</span> <span>false</span><span>;
           }
       }
       </span><span>else</span><span>
       {
           </span><span>return</span> <span>false</span><span>;
       }
   }

   </span><span>function</span> _setOptions(<span>$option</span><span>)
   {
       </span><span>$allow_options</span> = <span>array</span><span>(
                   </span>'PageSize',
                   'CurrentPageID',
                   'sql',
                   'numItems'<span>
       );

       </span><span>foreach</span> ( <span>$option</span> <span>as</span> <span>$key</span> => <span>$value</span><span> )
       {
           </span><span>if</span> ( <span>in_array</span>(<span>$key</span>, <span>$allow_options</span>) && (<span>$value</span> != <span>null</span><span>) )
           {
               </span><span>$this</span>-><span>$key</span> = <span>$value</span><span>;
           }
       }

       </span><span>return</span> <span>true</span><span>;
   }
}
</span>?>
<span>php
</span><span>//</span><span> FileName: test_pager.php
// 这是一段简单的示例代码,前边省略了使用pear db类建立数据库连接的代码 </span>
<span>require</span> "Pager.class.php"<span>; 
</span><span>if</span> ( <span>isset</span>(<span>$_GET</span>['page'<span>]) )
{
   </span><span>$page</span> = (int)<span>$_GET</span>['page'<span>];
}
</span><span>else</span><span>
{
   </span><span>$page</span> = 1<span>;
} 
</span><span>$sql</span> = "select * from table order by id"<span>; 
</span><span>$pager_option</span> = <span>array</span><span>(
       </span>"sql" => <span>$sql</span>,
       "PageSize" => 10,
       "CurrentPageID" => <span>$page</span><span>
); 
</span><span>if</span> ( <span>isset</span>(<span>$_GET</span>['numItems'<span>]) )
{
   </span><span>$pager_option</span>['numItems'] = (int)<span>$_GET</span>['numItems'<span>];
} 
</span><span>$pager</span> = @<span>new</span> Pager(<span>$pager_option</span><span>); 
</span><span>$data</span> = <span>$pager</span>-><span>getPageData(); 
</span><span>if</span> ( <span>$pager</span>-><span>isFirstPage )
{
   </span><span>$turnover</span> = "首页||"<span>;
}
</span><span>else</span><span>
{
   </span><span>$turnover</span> = "<a href="?page=1&numItems=%22.<span>%24pager</span>->numItems.%22">首页</a>|<a href="?page=%22.<span>%24pager</span>->PreviousPageID.%22&numItems=%22.<span>%24pager</span>->numItems.%22"></a>|"<span>;
} 
</span><span>if</span> ( <span>$pager</span>-><span>isLastPage )
{
   </span><span>$turnover</span> .= "|尾页"<span>;
}
</span><span>else</span><span>
{
   </span><span>$turnover</span> .= "<a href="?page=%22.<span>%24pager</span>->NextPageID.%22&numItems=%22.<span>%24pager</span>->numItems.%22"></a>|<a href="?page=%22.<span>%24pager</span>->numPages.%22&numItems=%22.<span>%24pager</span>->numItems.%22">尾页</a>"<span>;
}
</span>?>
Copier après la connexion

需要说明的地方有两个:
这个类仅仅处理数据,并不负责处理显示,因为我觉得将数据的处理和结果的显示都放到一个类里边实在是有些勉强。显示的时候情况和要求多变,不如自己根据类给出的结果处理,更好的方法是根据这个Pager类继承一个自己的子类来显示不同的分页,比如显示用户分页列表可以:

<span>php
</span><span>Class</span> MemberPager <span>extends</span><span> Pager
{
   </span><span>function</span><span> showMemberList()
   {
       </span><span>global</span> <span>$db</span><span>;

       </span><span>$data</span> = <span>$this</span>-><span>getPageData(); 
</span><span>//</span><span> 显示结果的代码
       // ......</span>
<span>   }
} 
</span><span>//</span><span>/ 调用</span>
<span>if</span> ( <span>isset</span>(<span>$_GET</span>['page'<span>]) )
{
   </span><span>$page</span> = (int)<span>$_GET</span>['page'<span>];
}
</span><span>else</span><span>
{
   </span><span>$page</span> = 1<span>;
} 
</span><span>$sql</span> = "select * from members order by id"<span>; 
</span><span>$pager_option</span> = <span>array</span><span>(
       </span>"sql" => <span>$sql</span>,
       "PageSize" => 10,
       "CurrentPageID" => <span>$page</span><span>
); 
</span><span>if</span> ( <span>isset</span>(<span>$_GET</span>['numItems'<span>]) )
{
   </span><span>$pager_option</span>['numItems'] = (int)<span>$_GET</span>['numItems'<span>];
} 
</span><span>$pager</span> = @<span>new</span> MemberPager(<span>$pager_option</span><span>); 
</span><span>$pager</span>-><span>showMemberList();
</span>?>
Copier après la connexion

第二个需要说明的地方就是不同数据库的兼容性,在不同的数据库里截获一段结果的写法是不一样的。
mysql: select * from table limit offset, rows
pgsql: select * from table limit m offset n
......
所以要在类里边获取结果的时候需要使用pear db类的limitQuery方法。

Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn

Outils d'IA chauds

Undresser.AI Undress

Undresser.AI Undress

Application basée sur l'IA pour créer des photos de nu réalistes

AI Clothes Remover

AI Clothes Remover

Outil d'IA en ligne pour supprimer les vêtements des photos.

Undress AI Tool

Undress AI Tool

Images de déshabillage gratuites

Clothoff.io

Clothoff.io

Dissolvant de vêtements AI

AI Hentai Generator

AI Hentai Generator

Générez AI Hentai gratuitement.

Article chaud

Repo: Comment relancer ses coéquipiers
1 Il y a quelques mois By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Crystals d'énergie expliqués et ce qu'ils font (cristal jaune)
2 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: Comment obtenir des graines géantes
1 Il y a quelques mois By 尊渡假赌尊渡假赌尊渡假赌
Combien de temps faut-il pour battre Split Fiction?
4 Il y a quelques semaines By DDD

Outils chauds

Bloc-notes++7.3.1

Bloc-notes++7.3.1

Éditeur de code facile à utiliser et gratuit

SublimeText3 version chinoise

SublimeText3 version chinoise

Version chinoise, très simple à utiliser

Envoyer Studio 13.0.1

Envoyer Studio 13.0.1

Puissant environnement de développement intégré PHP

Dreamweaver CS6

Dreamweaver CS6

Outils de développement Web visuel

SublimeText3 version Mac

SublimeText3 version Mac

Logiciel d'édition de code au niveau de Dieu (SublimeText3)

Configuration du projet CakePHP Configuration du projet CakePHP Sep 10, 2024 pm 05:25 PM

Dans ce chapitre, nous comprendrons les variables d'environnement, la configuration générale, la configuration de la base de données et la configuration de la messagerie dans CakePHP.

Guide d'installation et de mise à niveau de PHP 8.4 pour Ubuntu et Debian Guide d'installation et de mise à niveau de PHP 8.4 pour Ubuntu et Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 apporte plusieurs nouvelles fonctionnalités, améliorations de sécurité et de performances avec une bonne quantité de dépréciations et de suppressions de fonctionnalités. Ce guide explique comment installer PHP 8.4 ou mettre à niveau vers PHP 8.4 sur Ubuntu, Debian ou leurs dérivés. Bien qu'il soit possible de compiler PHP à partir des sources, son installation à partir d'un référentiel APT comme expliqué ci-dessous est souvent plus rapide et plus sécurisée car ces référentiels fourniront les dernières corrections de bogues et mises à jour de sécurité à l'avenir.

Date et heure de CakePHP Date et heure de CakePHP Sep 10, 2024 pm 05:27 PM

Pour travailler avec la date et l'heure dans cakephp4, nous allons utiliser la classe FrozenTime disponible.

Téléchargement de fichiers CakePHP Téléchargement de fichiers CakePHP Sep 10, 2024 pm 05:27 PM

Pour travailler sur le téléchargement de fichiers, nous allons utiliser l'assistant de formulaire. Voici un exemple de téléchargement de fichiers.

Routage CakePHP Routage CakePHP Sep 10, 2024 pm 05:25 PM

Dans ce chapitre, nous allons apprendre les sujets suivants liés au routage ?

Discuter de CakePHP Discuter de CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP est un framework open source pour PHP. Il vise à faciliter grandement le développement, le déploiement et la maintenance d'applications. CakePHP est basé sur une architecture de type MVC à la fois puissante et facile à appréhender. Modèles, vues et contrôleurs gu

CakePHP créant des validateurs CakePHP créant des validateurs Sep 10, 2024 pm 05:26 PM

Le validateur peut être créé en ajoutant les deux lignes suivantes dans le contrôleur.

Comment configurer Visual Studio Code (VS Code) pour le développement PHP Comment configurer Visual Studio Code (VS Code) pour le développement PHP Dec 20, 2024 am 11:31 AM

Visual Studio Code, également connu sous le nom de VS Code, est un éditeur de code source gratuit – ou environnement de développement intégré (IDE) – disponible pour tous les principaux systèmes d'exploitation. Avec une large collection d'extensions pour de nombreux langages de programmation, VS Code peut être c

See all articles