Home Backend Development PHP Tutorial Detailed explanation of PHP paging principle

Detailed explanation of PHP paging principle

Mar 16, 2017 pm 03:48 PM
php Pagination principle

Before reading this article, please make sure you have mastered some knowledge of PHP and the basics of MYSQL query operations.

As a Web program, it often has to deal with countless data, such as member data and article data. If there are only a few dozen members, it is easy to handle. It can be displayed on one page, but what if If your website has thousands or even hundreds of thousands of members, opening them all on one page will be a torture for both the browser and the viewer. Moreover, if there are hundreds of millions of data, querying them once from the database will put pressure on the server. It's a big deal, it's not the right way to do it.

I believe that every novice learning PHP will have a headache about paging, but with this silent post, you will definitely pat your head and say, hey, it turns out that paging is so simple? Indeed, please take a deep breath of fresh air now and listen carefully as Silence explains it to you bit by bit.

Suppose we want to process 1,000 pieces of data and display 10 pieces on each page. In this case, it will be displayed in 100 pages. Let's first take a look at how to extract 10 pieces of information in mysql.

Select * from table limit 0,10
Copy after login

The above is a very simple mysql query statement. Its function is to extract 10 pieces of data from a table named table and obtain the values ​​of all fields. The usage of limit 0,10 is: limit starting point, the amount to be extracted

The key part is in this paragraph "limit 0,10", where 0 is the starting point, and then 10 is to display 10 pieces of data, so we need to use 10 as the starting point, and how to write the 20th piece of data?

Perhaps a lot of people say "limit 10,20" outright! Oh, this is wrong. The correct way to write it is "limit 10,10". The parameter after it is not the end point but the number to be extracted. Remember.

Understand how to extract 10 pieces of data, then extracting 1,000 pieces means doing this kind of query 100 times, which means doing the following query:

Limit 0,10                                                             . Page
Limit 10,10                                                                                                                                                                                                                                                             Yet? Yes, the first parameter increases by 10 every time the page is turned, but the second parameter remains unchanged.
That is to say, if we try to change the value of the first parameter according to the number of pages, we can display the data in pages. How about it? Is the principle very simple?

But how to change the value of the first parameter based on the number of pages? First, we need to have a page number value, which can be obtained using the GET method of the URL.
For example, index.php?page=18
I believe most of you are familiar with this thing. This kind of URL address can be found everywhere. The function of the page parameter is to pass in the number of pages to be displayed.

Let’s take a look at how it is implemented through a piece of code:

<?php

/*

Author:默默
Date :2006-12-03

*/

$page=isset($_GET[&#39;page&#39;])?intval($_GET[&#39;page&#39;]):1;        //这句就是获取page=18中的page的值,假如不存在page,那么页数就是1。
$num=10;         //每页显示10条数据

$db=mysql_connect("host","name","pass");           //创建数据库连接
$select=mysql_select_db("db",$db);                 //选择要操作的数据库

/*
首先咱们要获取数据库中到底有多少数据,才能判断具体要分多少页,总页数 具体的公式就是
总数据数 除以 每页显示的条数,有余进一 。
也就是说10/3=3.3333=4 有余数就要进一。
*/

$total=mysql_num_rows(mysql_query("select * from table")); //查询数据的总数total
$pagenum=ceil($total/$num);      //获得总页数 pagenum

//假如传入的页数参数apge 大于总页数 pagenum,则显示错误信息
If($page>$pagenum || $page == 0){
       Echo "Error : Can Not Found The page .";
       Exit;
}

$offset=($page-1)*$num;         //获取limit的第一个参数的值 offset ,假如第一页则为(1-1)*10=0,第二页为(2-1)*10=10。             (传入的页数-1) * 每页的数据 得到limit第一个参数的值

$info=mysql_query("select * from table limit $offset,$num ");   //获取相应页数所需要显示的数据
While($it=mysql_fetch_array($info)){
       Echo $it[&#39;name&#39;]."<br />";
}                                                              //显示数据

For($i=1;$i<=$pagenum;$i++){

       $show=($i!=$page)?"<a href=&#39;index.php?page=".$i."&#39;>$i</a>":"<b>$i</b>";
       Echo $show." ";
}

/*显示分页信息,假如是当页则显示粗体的数字,其余的页数则为超连接,假如当前为第三页则显示如下
1 2 3 4 5 6
*/
?>
Copy after login

If you read the above code carefully, replace the database connection and query tables with yours, Then you can see its execution effect.

Isn’t it very simple? Just use your brain to make it display more personalized. Let me give you a small question: how to implement the format of "Homepage, Previous Page, Next Page, Last Page" What about paging?

Summary:

Prototype: Select * from table limit 0,10

Program: select * from table limit $offset,$num ($offset value is: pass The number of pages entered - 1 $num is the data displayed on each page, mostly a fixed constant value) Total number of pages: % of total data The number of items displayed on each page, if there is any excess int totalPage=( (totalCount%NUM)==0)?totalCount/NUM:totalCount/NUM+1;
limit usage: limit starting point, the number to be extracted

But it should be noted that: must be added order by , make sure to query in ascending or descending order, otherwise you will not know which direction to start the query when querying. But be sure to pay attention to the order: the correct one is select * from user order by id desc limit 0,10;

For more detailed explanations of PHP paging principles and related articles, please pay attention to the PHP Chinese website!

Related articles:

Use PHP to implement simple paging class and its detailed usage

php paging PHP paging display production detailed explanation

php paging class 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 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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles