search
HomeBackend DevelopmentPHP TutorialPaging source and paging class in php_PHP tutorial

The so-called paging display means that the result set in the database is artificially divided into sections for display. Two initial parameters are required here: How many records per page ($PageSize)?

What page is the current page ($CurrentPageID)?
Now just give me another result set and I can display a specific result.
As for other parameters, such as: previous page ($PReviousPageID), next page ($NextPageID), total number of pages ($numPages), etc., they can all be obtained based on the previous things.
Taking the MySQL database as an example, if you want to intercept a certain piece of content from the table, the sql statement can be used: select * from table limit offset, rows. Take a look at the following set of SQL statements and try to find the rules.
The first 10 records: select * from table limit 0,10
Records 11 to 20: select * from table limit 10,10
Records 21 to 30: select * from table limit 20,10

This set of sql statements is actually the sql statement for fetching data from each page of the table when $PageSize=10. We can summarize such a template:
select * from table limit ($CurrentPageID – 1) * $PageSize, $PageSize
Take this template and substitute the corresponding values ​​​​into the above set of SQL statements to see if that is the case. After solving the most important problem of how to obtain the data, all that is left is to pass the parameters, construct the appropriate SQL statement and then use PHP to obtain the data from the database and display it. Below I will explain it with specific code.
3. Simple code
Please read the following code in detail, debug and run it yourself, it is best to modify it and add your own functions, such as search, etc.
[php]

The code is as follows Copy code
 代码如下 复制代码

// 建立数据库连接
$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 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就可以很简单的用得到的二维数组来显示结果
?>

// Establish database connection $link = mysql_connect(“localhost”, “mysql_user”, “mysql_passWord”) or die(“Could not connect: ” . mysql_error()); // Get the current page number if( isset($_GET['page']) ){ $page = intval( $_GET['page'] ); } else{ $page = 1; } //Number per page $PageSize = 10; // Get the total data volume $sql = “select count(*) as amount from table”; $result = mysql_query($sql); $row = mysql_fetch_row($result); $amount = $row['amount']; // Calculate how many pages there are in total if( $amount ){ if ($ amount & lt; $ page_size) {$ page_count = 1;} // If the total data amount is less than $ pageSize, then there is only one page if( $amount % $page_size ){                                                                                                                                                   $page_count = (int)($amount / $page_size) + 1;                        //If there is a remainder, the number of pages is equal to the total data amount divided by the number of pages, rounded up and plus one }else{ $ page_count = $ amount /$ page_size; // If there is no more number, the number of pages is equal to the total data volume divided by the results of each page } } else{ $page_count = 0; } // Page turning link $page_string = ”; if( $page == 1 ){ $page_string .= ‘First page|Previous page|’; } else{ $page_string .= 'First page|Previous page a>|'; } if( ($page == $page_count) || ($page_count == 0) ){ $page_string .= ‘next page|last page’; } else{ $page_string .= 'Next page| Last page'; } // Get data and return the result in two-dimensional array format 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(); } // There is no code to display the results, so that is beyond the scope of discussion. You can simply use the obtained two-dimensional array to display the results using foreach ?>

PHP paginator production, automatically generates faceted page numbers, JS calls functions

The code is as follows Copy code

class PageView{
/**page number**/
Public $pageNo = 1;
/**Page size**/
Public $pageSize = 20;
/**How many pages in total**/
Public $pageCount = 0;
/**Total number of records**/
Public $totalNum = 0;
/**Offset, starting line of current page**/
Public $offSet = 0;
/**Data per page**/
Public $pageData = array();

/**Is there a previous page**/
Public $hasPrePage = true;
/**Is there a next page**/
Public $hasNextPage = true;

public $pageNoList = array();

public $jsFunction ='jsFunction';
/**
* *
* @param unknown_type $count total number of rows
* @param unknown_type $size paging size
* @param unknown_type $string
​​*/
Public function __construct($count=0, $size=20,$pageNo=1,$pageData =array(),$jsFunction='jsFunction'){

$this->totalNum = $count;//Total number of records
           $this->pageSize = $size;//Size of each page
            $this->pageNo = $pageNo;
//Calculate the total number of pages
           $this->pageCount = ceil($this->totalNum/$this->pageSize);
           $this->pageCount = ($this->pageCountpageCount;
//Check pageNo
           $this->pageNo = $this->pageNo == 0 ? 1 : $this->pageNo;
$this->pageNo = $this->pageNo > $this->pageCount? $this->pageCount : $this->pageNo;

//Calculate offset
$this->offset = ( $this->pageNo - 1 ) * $this->pageSize;
//Calculate whether there is a previous page or a next page
            $this->hasPrePage = $this->pageNo == 1 ?false:true;

$this->hasNextPage = $this->pageNo >= $this->pageCount ?false:true;

$this->pageData = $pageData;
            $this->jsFunction = $jsFunction;

    }
    /**
* Paging algorithm
* @return
​​*/
    private function generatePageList(){
        $pageList = array();
        if($this->pageCount             for($i=0;$ipageCount;$i++){
                array_push($pageList,$i+1);
            }
        }else{
            if($this->pageNo                 for($i=0;$i                     array_push($pageList,$i+1);
                }
                array_push($pageList,-1);
                array_push($pageList,$this->pageCount);

            }else if($this->pageNo > $this->pageCount - 4){
                array_push($pageList,1);

                array_push($pageList,-1);
                for($i=5;$i>0;$i--){
                    array_push($pageList,$this->pageCount - $i+1);
                }
            }else if($this->pageNo > 4 && $this->pageNo pageCount - 4){
                array_push($pageList,1);
                array_push($pageList,-1);

                array_push($pageList,$this->pageNo -2);
                array_push($pageList,$this->pageNo -1);
                array_push($pageList,$this->pageNo);
                array_push($pageList,$this->pageNo + 1);
                array_push($pageList,$this->pageNo + 2);

                array_push($pageList,-1);
                array_push($pageList,$this->pageCount);

            }
        }
        return $pageList;
    }

    /***
* Create paging control
* @param
* @return String
​*/
    public function echoPageAsDiv(){
        $pageList = $this->generatePageList();

        $pageString ="

");
        return $pageString;
    }
}

?>

-->

PHP调用

 代码如下
 代码如下 复制代码


$pageNo = $_GET['pageNo'];
if(empty($pageNo)){
}
//分页数据
$pageData = News::getNewsPage($pageNo,$pageSize);
       //取得总行数
$count = News::getNewsCount();
        //创建分页器
$p = new PageView($count['0']['TOTAL'],$pageSize,$pageNo,$pageData);
     //生成页码
$pageViewString = $p->echoPageAsDiv();

复制代码
$pageNo = $_GET['pageNo'];

if(empty($pageNo)){

} $pageData = News::getNewsPage($pageNo,$pageSize);        //取得总行数 $count = News::getNewsCount();         //创建分页器 $p = new PageView($count['0']['TOTAL'],$pageSize,$pageNo,$pageData);      //生成页码 $pageViewString = $p->echoPageAsDiv();
http://www.bkjia.com/PHPjc/628968.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/628968.htmlTechArticle所谓分页显示,也就是将数据库中的结果集人为的分成一段一段的来显示,这里需要两个初始的参数:每页多少条记录($PageSize)? 当前是...
Statement
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
Beyond the Hype: Assessing PHP's Role TodayBeyond the Hype: Assessing PHP's Role TodayApr 12, 2025 am 12:17 AM

PHP remains a powerful and widely used tool in modern programming, especially in the field of web development. 1) PHP is easy to use and seamlessly integrated with databases, and is the first choice for many developers. 2) It supports dynamic content generation and object-oriented programming, suitable for quickly creating and maintaining websites. 3) PHP's performance can be improved by caching and optimizing database queries, and its extensive community and rich ecosystem make it still important in today's technology stack.

What are Weak References in PHP and when are they useful?What are Weak References in PHP and when are they useful?Apr 12, 2025 am 12:13 AM

In PHP, weak references are implemented through the WeakReference class and will not prevent the garbage collector from reclaiming objects. Weak references are suitable for scenarios such as caching systems and event listeners. It should be noted that it cannot guarantee the survival of objects and that garbage collection may be delayed.

Explain the __invoke magic method in PHP.Explain the __invoke magic method in PHP.Apr 12, 2025 am 12:07 AM

The \_\_invoke method allows objects to be called like functions. 1. Define the \_\_invoke method so that the object can be called. 2. When using the $obj(...) syntax, PHP will execute the \_\_invoke method. 3. Suitable for scenarios such as logging and calculator, improving code flexibility and readability.

Explain Fibers in PHP 8.1 for concurrency.Explain Fibers in PHP 8.1 for concurrency.Apr 12, 2025 am 12:05 AM

Fibers was introduced in PHP8.1, improving concurrent processing capabilities. 1) Fibers is a lightweight concurrency model similar to coroutines. 2) They allow developers to manually control the execution flow of tasks and are suitable for handling I/O-intensive tasks. 3) Using Fibers can write more efficient and responsive code.

The PHP Community: Resources, Support, and DevelopmentThe PHP Community: Resources, Support, and DevelopmentApr 12, 2025 am 12:04 AM

The PHP community provides rich resources and support to help developers grow. 1) Resources include official documentation, tutorials, blogs and open source projects such as Laravel and Symfony. 2) Support can be obtained through StackOverflow, Reddit and Slack channels. 3) Development trends can be learned by following RFC. 4) Integration into the community can be achieved through active participation, contribution to code and learning sharing.

PHP vs. Python: Understanding the DifferencesPHP vs. Python: Understanding the DifferencesApr 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.

PHP: Is It Dying or Simply Adapting?PHP: Is It Dying or Simply Adapting?Apr 11, 2025 am 12:13 AM

PHP is not dying, but constantly adapting and evolving. 1) PHP has undergone multiple version iterations since 1994 to adapt to new technology trends. 2) It is currently widely used in e-commerce, content management systems and other fields. 3) PHP8 introduces JIT compiler and other functions to improve performance and modernization. 4) Use OPcache and follow PSR-12 standards to optimize performance and code quality.

The Future of PHP: Adaptations and InnovationsThe Future of PHP: Adaptations and InnovationsApr 11, 2025 am 12:01 AM

The future of PHP will be achieved by adapting to new technology trends and introducing innovative features: 1) Adapting to cloud computing, containerization and microservice architectures, supporting Docker and Kubernetes; 2) introducing JIT compilers and enumeration types to improve performance and data processing efficiency; 3) Continuously optimize performance and promote best practices.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use