1. Preface
Paging display is a very common method for browsing and displaying large amounts of data. It is one of the most common events in web programming. For veterans of web programming, writing such code is as natural as breathing, but for beginners, they often have no clue about this issue. Therefore, I wrote this article to explain this issue in detail, we strive to make friends who have read this article understand the principle and implementation methods of paging display. This article is suitable for beginners. All sample code is written in php.
2. Principles
The so-called paging display means that the result set in the database is manually divided into segments for display. Here two initial parameters are required:
How many records per page ($ PageSize )?
What is the current page ($ CurrentPageID )?
Now, you only need to give me another result set, so that I can display a specific result.
Other parameters, such as the previous page ($ PreviousPageID), next page ($ NextPageID), and total page ($ numPages), can all be obtained based on the front.
Take the mysql database as an example. If you want to extract some content from the table, you can use the SQL statement: select * from table limit offset, rows. Take a look at the following SQL statements and try to find the rule rate.
First 10 records: select * from table limit 0, 10
11th to 20 records: select * from table limit 10, 10
21st to 30 records: select * from table limit 20, 10
......
This set of SQL statements is the SQL statement used to retrieve data of each page in the table when $ PageSize = 10. We can summarize this template:
Select * from table limit ($ CurrentPageID-1) * $ PageSize, $ PageSize
Use this template to compare the corresponding values with the preceding SQL statements to see if this is the case. After solving the most important problem of how to obtain data, the rest is simply passing parameters, constructing appropriate SQL statements, and then using php to obtain data from the database and display it. I will describe the code below.
3. Simple code
Please read the following code in detail and debug and run it once. You 'd better modify it once and add your own functions, such as search.
<? Php
// Establish a database connection
$ Link = mysql_connect ("localhost", "mysql_user", "mysql_password ")
Or die ("cocould not connect:". mysql_error ());
// Obtain the current page number
If (isset ($ _ GET ['page']) {
$ Page = intval ($ _ GET ['page']);
}
Else {
$ Page = 1;
}
// Number of pages per page
$ PageSize = 10;