Backend Development
PHP Tutorial
PHP paging principle Paging code Detailed explanation of paging class production method examplesPHP paging principle Paging code Detailed explanation of paging class production method examples
This article mainly introduces the PHP paging principle, PHP paging code, and PHP paging class production tutorial in detail. It has a certain reference value. Interested friends can refer to it.
Paging display is A very common way to browse and display large amounts of data, and one of the most commonly handled 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.
1. Paging principle:
The so-called paging display means that the result set in the database is artificially divided into sections for display. Two steps are required here. Initial parameters:
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
11th to 20th records: select * from table limit 10,10
21st to 30th Records: select * from table limit 20,10
……
This set of sql statements is actually the sql statement that fetches each page of data in the table when $PageSize=10. We can summarize such a template:
SELECT * From Table Limit ($ CurrentPageid -1) * $ PageSize, $ PageSize
我们 The corresponding value is substituted with the SQL statement above. That's not 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.
2. Paging code description: five steps
The code is fully explained and can be copied to your own notepad for direct use
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<title>雇员信息列表</title>
</head>
<?php
//显示所有emp表的信息
//1.连接数据库
$conn=mysql_connect('localhost','root','1234abcd') or die('连接数据库错误'.mysql_error());
//2.选择数据库
mysql_select_db('empManage');
//3.选择字符集
mysql_query('set names utf8');
//4.发送sql语句并得到结果进行处理
//4.1分页[分页要发出两个sql语句,一个是获得$rowCount,一个是通过sql的limit获得分页结果。所以我们会获得两个结果集,在命名的时候要记得区分。
分页 (四个值 两个sql语句)。]
$pageSize=3;//每页显示多少条记录
$rowCount=0;//共有多少条记录
$pageNow=1;//希望显示第几页
$pageCount=0;//一共有多少页 [分页共有这个四个指标,缺一不可。由于$rowCount可以从服务器获得的,所以可以给予初始值为0;
$pageNow希望显示第几页,这里最好是设置为0;$pageSize是每页显示多少条记录,这里根据网站需求提前制定。
.$pageCount=ceil($rowCount/$pageSize),既然$rowCount可以初始值为0,那么$pageCount当然也就可以设置为0.四个指标,两个0 ,一个1,另一个为网站需求。]
//4.15根据分页链接来修改$pageNow的值
if(!empty($_GET['pageNow'])){
$pageNow=$_GET['pageNow'];
}[根据分页链接来修改$pageNow的值。]
$sql='select count(id) from emp';
$res1=mysql_query($sql);
//4.11取出行数
if($row=mysql_fetch_row($res1)){
$rowCount=$row[0];
}//[取得$rowCount,,进了我们就知道了$pageCount这两个指标了。]
//4.12计算共有多少页
$pageCount=ceil($rowCount/$pageSize);
$pageStart=($pageNow-1)*$pageSize;
//4.13发送带有分页的sql结果
$sql="select * from emp limit $pageStart,$pageSize";//[根据$sql语句的limit 后面的两个值(起始值,每页条数),来实现分页。以及求得这两个值。]
$res2=mysql_query($sql,$conn) or die('无法获取结果集'.mysql_error());
echo '<table border=1>';[ echo "<table border='1px' cellspacing='0px' bordercolor='red' width='600px'>";]
"<tr><th>id</th><th>name</th><th>grade</th><th>email</th><th>salary</th><th><a href='#'>删除用户</a></th><th><a href='#'>修改用户</a></th></tr>"; while($row=mysql_fetch_assoc($res2)){
echo "<tr><td>{$row['id']}</td><td>{$row['name']}</td><td>{$row['grade']}</td><td>{$row['email']}</td><td>{$row['salary']}</td><td><a href='#'>删除用户</a></td><td><a href='#'>修改用户</a></td></tr>"; }
echo '</table>';
//4.14打印出页码的超链接
for($i=1;$i<=$pageCount;$i++){
echo "<a href='?pageNow=$i'>$i</a> ";//[打印出页码的超链接]
}
//5.释放资源,关闭连接
mysql_free_result($res2);
mysql_close($conn);
?>
</html>
3. Simple paging category sharing
Now announce the production of a simple category. As long as you understand the principles and steps of this class, you will be able to understand other complex classes by analogy. No nonsense, just upload the source code and you can use it directly in your project.
Database operation code: mysqli.func.php
<?php
// 数据库连接常量
define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PWD', '');
define('DB_NAME', 'guest');
// 连接数据库
function conn()
{
$conn = mysqli_connect(DB_HOST, DB_USER, DB_PWD, DB_NAME);
mysqli_query($conn, "set names utf8");
return $conn;
}
//获得结果集
function doresult($sql){
$result=mysqli_query(conn(), $sql);
return $result;
}
//结果集转为对象集合
function dolists($result){
return mysqli_fetch_array($result, MYSQL_ASSOC);
}
function totalnums($sql) {
$result=mysqli_query(conn(), $sql);
return $result->num_rows;
}
// 关闭数据库
function closedb()
{
if (! mysqli_close()) {
exit('关闭异常');
}
}
?>Paging implementation code:
<?php
include 'mysqli.func.php';
// 总记录数
$sql = "SELECT dg_id FROM tb_user ";
$totalnums = totalnums($sql);
// 每页显示条数
$fnum = 8;
// 翻页数
$pagenum = ceil($totalnums / $fnum);
//页数常量
@$tmp = $_GET['page'];
//防止恶意翻页
if ($tmp > $pagenum)
echo "<script>window.location.href='index.php'</script>";
//计算分页起始值
if ($tmp == "") {
$num = 0;
} else {
$num = ($tmp - 1) * $fnum;
}
// 查询语句
$sql = "SELECT dg_id,dg_username FROM tb_user ORDER BY dg_id DESC LIMIT " . $num . ",$fnum";
$result = doresult($sql);
// 遍历输出
while (! ! $rows = dolists($result)) {
echo $rows['dg_id'] . " " . $rows['dg_username'] . "<br>";
}
// 翻页链接
for ($i = 0; $i < $pagenum; $i ++) {
echo "<a href=index.php?page=" . ($i + 1) . ">" . ($i + 1) . "</a>";
}
?>
Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study.
Related recommendations:
PHP Upload Excel file and import data to MySQL database
phpThrow Detailed explanation of exceptions and catching specific types of exceptions
##php array_merge_recursive Array merge
The above is the detailed content of PHP paging principle Paging code Detailed explanation of paging class production method examples. For more information, please follow other related articles on the PHP Chinese website!
PHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AMPHP 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 HistoryApr 18, 2025 am 12:25 AMPHP 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 GuideApr 18, 2025 am 12:24 AMPHP 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 LanguageApr 18, 2025 am 12:14 AMPHP 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 BeyondApr 18, 2025 am 12:10 AMPHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.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?Apr 17, 2025 am 12:25 AMPHP 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.
How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AMIn PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.
PHP vs. Python: Use Cases and ApplicationsApr 17, 2025 am 12:23 AMPHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.


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

WebStorm Mac version
Useful JavaScript development tools

Atom editor mac version download
The most popular open source editor

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

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

SublimeText3 Mac version
God-level code editing software (SublimeText3)





