Home Backend Development PHP Tutorial Detailed explanation of PHP application paging display production_PHP tutorial

Detailed explanation of PHP application paging display production_PHP tutorial

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

  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、简单代码

  请详细阅读以下代码,自己调试运行一次,最好把它修改一次,加上自己的功能,比如搜索等等。

<?php
 // 建立数据库连接
 $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 .= '<a href=?page=1>第一页</a>|<a href=?page='.($page-1).'>上一页</a>|';
 }
 if( ($page == $page_count) || ($page_count == 0) ){
  $page_string .= '下一页|尾页';
 }
 else{
  $page_string .= '<a href=?page='.($page+1).'>下一页</a>|<a href=?page='.$page_count.'>尾页</a>';
 }
 // 获取数据,以二维数组格式返回结果
 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类进行处理

<?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(
     'PageSize',
     'CurrentPageID',
     'sql',
     'numItems'
   );

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

 return true;
 }
}
?>
<?php
// FileName: test_pager.php
// This is a simple sample code, the front part is omitted Code for establishing database connection using pear db class
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 = "<a href='?page=1&numItems=".$pager->numItems."'>Homepage</a>|<a href='?page =".$pager-> PreviousPageID."&numItems=".$pager->numItems."'>Previous page</a>|";
}
if ( $pager->isLastPage )
{
 $turnover .= "Next page|Last page";
}
else
{
 $turnover .= "<a href='?page=".$pager ->NextPageID."&numItems=".$pager->numItems."'>Next page</a>|<a    href='?page=".$pager->numPages."&numItems=".$pager- >numItems."'>Last page</a>";
}
?>

There are two things that need to be explained:

This class only processes data and I am not responsible for handling the 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( ; ]) )
{
 $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 different databases For compatibility, the way to write a section of results in different databases is different.

mysql: select * from table limit offset, rows
pgsql: select * from table limit m offset n
...

So it needs to be obtained in the class When obtaining results, you need to use the limitQuery method of the pear db class.



http://www.bkjia.com/PHPjc/313771.html

www.bkjia.com

true

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

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

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 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)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1252
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

See all articles