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

Detailed explanation of PHP pagination display production_PHP tutorial

WBOY
Release: 2016-07-21 16:08:01
Original
3143 people have browsed it

1、前言

分页显示是一种非常常见的浏览和显示大量数据的方法,属于web编程中最常处理的事件之一。对于web编程的老手来说,编写这种代码实在是和呼吸一样自然,但是对于初学者来说,常常对这个问题摸不着头绪,因此特地撰写此文对这个问题进行详细的讲解,力求让看完这篇文章的朋友在看完以后对于分页显示的原理和实现方法有所了解。本文适合初学者阅读,所有示例代码均使用php编写。

2、原理

所谓分页显示,也就是将数据库中的结果集人为的分成一段一段的来显示,这里需要两个初始的参数:

每页多少条记录($PageSize)?
当前是第几页($CurrentPageID)?

现在只要再给我一个结果集,我就可以显示某段特定的结果出来。
至于其他的参数,比如:上一页($PreviousPageID)、下一页($NextPageID)、总页数($numPages)等等,都可以根据前边这几个东西得到。
以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、简单代码
请详细阅读以下代码,自己调试运行一次,最好把它修改一次,加上自己的功能,比如搜索等等。

// 建立数据库连接
$link = mysql_connect("localhost", "mysql_user", "mysql_password")
or die("Could not connect: " . mysql_error());
// 获取当前页数
if( isset($_GET['page']) ){
$page = intval( $_GET['page'] );
}
else{
$page = 1;
}
// 每页数量
$PageSize = 10;
// 获取总数据量
$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; } //如果总数据量小于$PageSize,那么只有一页
if( $amount % $page_size ){ //取总数据量除以每页数的余数
$page_count = (int)($amount / $page_size) + 1; //如果有余数,则页数等于总数据量除以每页数的结果取整再加一
}else{
$page_count = $amount / $page_size; //如果没有余数,则页数等于总数据量除以每页数的结果
}
}
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 .= '下一页|尾页';
}
// 获取数据,以二维数组格式返回结果
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就可以很简单的用得到的二维数组来显示结果
?>

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

// 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方法保证数据库兼容性

           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...
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template