search
HomeBackend DevelopmentPHP TutorialA brief discussion on the fifth bullet of PHP---The Nine-Yang Magic of Pagination_PHP Tutorial

In the above article http://www.BkJia.com/kf/201204/128413.html I told you about the operating mechanism and use of recursive functions. I don’t know if you understand it. If you don’t understand, you can ask questions below. , I will help you answer it at any time.

In the past two days, many students have added questions to the paging when asking questions. So today I will tell you in detail the application of paging technology:

We often see beautiful pagination in some web applications,

Clicking the next page will display the content of the next page, which makes the page more beautiful.

Okay, after reading the explanation in this article, I believe that students can also write beautiful pagination

Now I have a data table named mytable with the following data:



id name pass age sex
1 Goudan wrw7921sqa5eb72c92a549dd5avfr112 20 1
2 Gao Fushuai vdf79218965eb72c92a549dd5a334534 20 0
3 Jie Ge gbj792saa65eb72c92a549dd5avfd321 22 1
4 Band of Brothers 45379218965eb72ccdd549dd5a330342 24 1
5 lampbrothers cdc79218965eb72c92a549dd5vsfdwsx 24 1
6 lamp ret79218965eb72c92a549dd5a33bgyt 25 0
7 php 123qwe18965eb72c92a549dd5a330875 26 1
8 mysql 76e79218965eb72c92a549ddvfdd0dsa 28 0
9 apache 54ebnm18965eb72c92a549dd5a330cxz 30 1


First, make a paging link
echo "Previous page
";
echo "Next page
";
echo "Total items";
?>

Let’s think about it, click on the previous page, the current page number will be reduced by one, and the data of the previous page will be displayed

Suppose we use a variable $page to control the current page number, then should the previous page be $page-1

The page number of the next page is $page+1

So our link above should be changed to:
echo "Previous page
";
echo "Next page
";
?>


This way everyone should understand clearly how to pass the page numbers of the previous and next pages

But in actual development, it is impossible for a web software to allow users to pass in page numbers. When users visit the page, they will only access index.php

So we will handle this situation accordingly:
$page = !empty($_GET['page'])?$_GET['page']:1
?>

If our $page is not given at this time, that is, $_GET['page'] is empty, we directly assign the value 1 to $page

Next step, let’s display the data separately, that is to say, the first page only displays the data of the first page, and the second page only displays the data of the second page.....Only the Nth page is displayed. Data on page N

In this case, we need to operate the sql statement. If we want to display the data in pages, we use the limit clause of the sql statement

Okay, then we think, if each page of data only displays 5 records, what should the SQL statement look like?

Then ours

First page:
Should the displayed data from the first to fifth items be "limit 0,5";

Second page:
The displayed data from the sixth to the tenth item should be "limit 5,5";

Page 3:
The displayed data from the 11th to 15th items should be “limit 10,5”;

............

Let’s look at a pattern,

Look carefully, should our nth page be

limit (n-1)*Number of items displayed on each page, number of items displayed on each page

In other words, the data we need include the current page number and the number of items displayed on each page

Okay, as we just said, we can get the current page number through $_GET['page'], then we can use a variable to define the number of items displayed on each page. Skilled students can define a constant and put it Go to the configuration file,

Here we use variables to define and set the page size to 5

$page = $_GET['page'];

$pagesize = 5;

The limit clause of the assembled sql statement should be "limit ($page-1)*$pagesize,$pagesize"

At this point, we have been able to paginate the data,

But if we want to get the total number of pages, we also need to count the total number of records from the database

$sql = "select count(*) from mytable";

$result = mysql_query($sql);

We can take out the execution result using the mysql_result() function.

$count = mysql_result($result,0);

Okay, then our current total number of records is $count,

Now our total number of data items is 9, and each page displays 5 items. Think about it, should our total number of pages be 2, that is, ceil(9/5)=2

The formula for calculating the total number of pages is ceil($count/$pagesize),


Okay, all the data we need has been obtained, finally assembled into a sql statement and displayed, it should be:
//Set how many records to display on each page
$pagesize = 5;
//Get the current page number
$page = !empty($_GET['page'])?$_GET['page']:1;
//Total number of records
$sql = "select count(*) from mytable";
$result = mysql_query($sql);
$count = mysql_result($result,0);
//How many pages are there in total
$page_count = ceil($count/$pagesize);
//Determine whether the current given page number is out of bounds
if($page $page=1;
}elseif($page>$page_count){
$page=$page_count;
}
//Start assembling sql statements
$sql = "select id,name,age,sex from mytable limit ".($page-1)*$pagesize.','.$pagesize;
//Send sql statement
$result = mysql_query($sql);
//Output form
echo "

";
echo "";
echo "";
echo "";
//Define gender array
$sex = array('male','female');
//Traverse the output result set
while($row = mysql_fetch_assoc($result)){
echo "";
echo "";
echo "";
echo "";
[backcolor=#ffffff][color=#008ef1]echo "";[/color][/backcolor]
}
echo "
Username Age Gender
".$row['name']."".$row['age']."".$sex[$row['sex']]."
";
//Add pagination to display links
$up = (($page-1) $down = (($page+1)>$page_count)?$page_count:($page+1);
echo "Previous page ";
echo "Next page ";
echo "Total".$page_count."page";
echo "Current page ".$page." ";
echo "Total".$count."records";
?>
Okay, so we have added the paging function. How about it? Isn’t it very simple?

Let me summarize the specific steps of paging:

Step one: Set the page size (how many items to display on each page)

Step 2: Get the current page number

Step 3: Get the total number of records

Step 4: Get the total number of pages

Step 5: Determine whether the current given page number is out of bounds

Step 6: Assemble sql statement

Step 7: Send sql statement to mysql server

Step 8: Traverse the result set and output

Step 9: Add pagination links

As long as you remember the above martial arts secrets of Jie Ge’s nine-yang magic skill, I believe that students will be able to leisurely ride through the martial arts killing fields of PHP



Author zdrjlamp

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/478277.htmlTechArticleI told you about it above http://www.2cto.com/kf/201204/128413.html I don’t know if you understand the operating mechanism and use of recursive functions. If you don’t understand, you can ask questions below. I...
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 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.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

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

Video Face Swap

Video Face Swap

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

Hot Tools

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

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools