
1. Encapsulating configuration information
1. We can make a configuration file config.php. Set all the configurations that need to be used as constants. The code is as follows:
<?php //数据库服务器 define('DB_HOST', 'localhost'); //数据库用户名 define('DB_USER', 'root'); //数据库密码 define('DB_PWD', 'secret'); //库名 define('DB_NAME', 'book'); //字符集 define('DB_CHARSET', 'utf8');
2. 2. We extract the connection.php page. When we need to connect to the database in the future, we only need to include the connection.php file.
The code is as follows:
<?php
include 'config.php';$conn = mysqli_connect(DB_HOST, DB_USER, DB_PWD, DB_NAME);
if (mysqli_errno($conn))
{ mysqli_error($conn);
exit;
}
mysqli_set_charset($conn, DB_CHARSET);
?>We can realize the database connection by directly including the connection.php file in each file in the future:
include 'connection.php';
2. Display paging implementation
# Pages must be implemented to include the following basic elements:

We are in control When it comes to page numbers, page number control is achieved by passing in the page number value in the URL address bar. By appending the page number-related information to page.php, we can calculate more effective information. The effect of url controlling paging is as follows:

In the code implementation, these two values are actually realized through the offset (offset) and quantity (num) after limit. of paging.
limit offset , num

#Assume 5 items are displayed per page. The final formula for controlling the limit in paging is as follows:
offset的值为 (n-1)*5 num 为规定的5
3. Implementation steps;
1. Calculate Parameters required for paging
1-1, total number
通过查询user表的count(id),得到总数$count。 $count_sql = 'select count(id) as c from user'; $result = mysqli_query($conn, $count_sql); $data = mysqli_fetch_assoc($result); //得到总的用户数 $count = $data['c'];
1-2, current page
When you first enter the page.php page , the url is http://www.php.com/page.php, and there is no ?page=1 page identification number after it.
So we need to manually create a page identification number and pass it to the current page number variable $page.
We are afraid that there are decimals in the page passed by the user, so we do a forced type conversion: (int) $_GET['page'].
The first way of writing:
$page = isset($_GET['page']) ? (int) $_GET['page'] : 1;
The second way of writing:
if (isset($_GET['page'])) {
$page = (int) $_GET['page'];
} else {
$page = 1;
}1-3, the last page
Every One page must be an integer. Just like math in elementary school. On average, 5.6 people should prepare how many apples. The answer must be 6.
If the page comes out with 20.3 pages, the rounding function ceil must be used. Let the number of pagination become 21.
We divide the total number by the number of data displayed on each page to get the total number of pages.
//每页显示数 $num = 5; $total = ceil($count / $num);
1-4. Control of abnormal situations on upper and lower pages
What should I do if the user clicks the previous page on the first page and clicks the next page on the last page? ?
In this case, the data will exceed the range, causing no data to be displayed when we paginate.
Obviously this unusual situation needs to be taken into account. Therefore, if the first page is subtracted by one during paging, we make it the first page.
When adding one to the last page, we make it the last page, that is, the exception control is completed.
if ($page <= 1) {
$page = 1;
}
if ($page >= $total) {
$page = $total;
}2. SQL statement
We said before that the core of paging is to control the number of displays per page through the offset and num in the SQL statement.
$num = 5; $offset = ($page - 1) * $num;
We apply $num and $offset to the SQL statement:
$sql = "select id,username,createtime,createip from user order by id desc limit $offset , $num";
Control the paging value in the URI
echo '<tr>
<td colspan="5">
<a href="page.php?page=1">首页</a>
<a href="page.php?page=' . ($page - 1) . '">上一页</a>
<a href="page.php?page=' . ($page + 1) . '">下一页</a>
<a href="page.php?page=' . $total . '">尾页</a>
当前是第 ' . $page . '页 共' . $total . '页
</td>
</tr>';4. Overall code implementation
include 'connection.php';
$count_sql = 'select count(id) as c from user';
$result = mysqli_query($conn, $count_sql);
$data = mysqli_fetch_assoc($result);
//得到总的用户数
$count = $data['c'];
$page = isset($_GET['page']) ? (int) $_GET['page'] : 1;
/*
if (isset($_GET['page'])) {
$page = (int) $_GET['page'];
} else {
$page = 1;
}
*/
//每页显示数
$num = 5;
//得到总页数
$total = ceil($count / $num);
if ($page <= 1) {
$page = 1;
}
if ($page >= $total) {
$page = $total;
}
$offset = ($page - 1) * $num;
$sql = "select id,username,createtime,createip from user order by id desc limit $offset , $num";
$result = mysqli_query($conn, $sql);
if ($result && mysqli_num_rows($result)) {
//存在数据则循环将数据显示出来
echo '| ' . $row['username'] . ' | '; echo '' . date('Y-m-d H:i:s', $row['createtime']) . ' | '; echo '' . long2ip($row['createip']) . ' | '; echo '编辑用户 | '; echo '删除用户 | '; echo '
| 首页 上一页 下一页 尾页 当前是第 ' . $page . '页 共' . $total . '页 | ||||
The above content realizes a simple paging function. For more related content, please visit the PHP Chinese website: PHP Video Tutorial
The above is the detailed content of Principles and steps to implement paging in php. For more information, please follow other related articles on the PHP Chinese website!
PHP's Purpose: Building Dynamic WebsitesApr 15, 2025 am 12:18 AMPHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.
PHP: Handling Databases and Server-Side LogicApr 15, 2025 am 12:15 AMPHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.
How do you prevent SQL Injection in PHP? (Prepared statements, PDO)Apr 15, 2025 am 12:15 AMUsing preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.
PHP and Python: Code Examples and ComparisonApr 15, 2025 am 12:07 AMPHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.
PHP in Action: Real-World Examples and ApplicationsApr 14, 2025 am 12:19 AMPHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.
PHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AMPHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.
PHP and Python: Comparing Two Popular Programming LanguagesApr 14, 2025 am 12:13 AMPHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.
The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AMPHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 English version
Recommended: Win version, supports code prompts!

WebStorm Mac version
Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Zend Studio 13.0.1
Powerful PHP integrated development environment






