1. Foreword
Paging display is a very common method of browsing and displaying large amounts of data. It is one of the most commonly processed events in web programming. For veterans of web programming, writing this kind of code is as natural as breathing, but for beginners, they are often confused about this issue, so I specially wrote this article to explain this issue in detail, and strive to let readers Friends who have finished this article will have some understanding of the principles and implementation methods of paging display. This article is suitable for beginners to read, and all sample codes are written in PHP.
2. Principle
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 as long as you give me another result set, 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
The 11th to 20th records: select * from table limit 10,10
The 21st to 30th records: select * from table limit 20 ,10
……
This set of sql statements is actually the sql statement to retrieve data from each page of the table when $PageSize=10. We can summarize such a template:
select * from table limit ($CurrentPageID - 1) * $PageSize, $PageSize
Use this template to substitute the corresponding value and compare it with 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 once and add your own functions, such as search, etc.
<?php
// Establish a 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 of pages per page
$PageSize = 10;