php paging query is written like "select word from ufeature.spam_accuse_word_list where flag='0'". This statement is a sql query statement and you can get the query results.

The operating environment of this article: Windows 7 system, PHP version 7.1, Dell G3 computer.
php How to write paging query? 3 ways to implement paging function in php
Directly upload the code, I hope everyone will read it carefully.
Method 1: SQL query to perform paging, you need to call several functions, see the script for details:
1.pager.class.php
<?php
class pager {
public $sql; //SQL查询语句
public $datanum; //查询所有的数据总记录数
public $page_size; //每页显示记录的条数
protected $_errstr;
protected $_conn;
protected $_query_id;
public function query($query)///这个函数有问题,暂时可以不用
{
$ret = false;
if (!empty($query)) {
if ($this->_conn === false || !is_resource($this->_conn)) {
warningLog(__METHOD__ . ': query sql with no connection', true);
return false;
}
$this->_query_id = @mysql_query($query, $this->_conn);
if ($this->_query_id === false) {
$this->_errstr = @mysql_error();
$ret = false;
} else {
$this->_errstr = 'SUCCESS';
$ret = $this->_query_id;
}
}
$msg = ($ret === false) ? 'false' : strval($ret);
debugLog(__METHOD__.": [$msg] returned for sql query [$query]");
return $ret;
}
function __construct($sql,$page_size) {
$result = mysql_query($sql);
$datanum = mysql_num_rows($result);
$this->sql=$sql;
$this->datanum=$datanum;
$this->page_size=$page_size;
}
//当前页数
public function page_id() {
if($_SERVER['QUERY_STRING'] == ""){
return 1;
}elseif(substr_count($_SERVER['QUERY_STRING'],"page_id=") == 0){
return 1;
}else{
return intval(substr($_SERVER['QUERY_STRING'],8));
}
}
//剩余url值
public function url() {
if($_SERVER['QUERY_STRING'] == ""){
return "";
}elseif(substr_count($_SERVER['QUERY_STRING'],"page_id=") == 0){
return "&".$_SERVER['QUERY_STRING'];
}else{
return str_replace("page_id=".$this->page_id(),"",$_SERVER['QUERY_STRING']);
}
}
//总页数
public function page_num() {
if($this->datanum == 0){
return 1;
}else{
return ceil($this->datanum/$this->page_size);
}
}
//数据库查询的偏移量
public function start() {
return ($this->page_id()-1)*$this->page_size;
}
//数据输出
public function sqlquery() {
return $this->sql." limit ".$this->start().",".$this->page_size;
}
//获取当前文件名
private function php_self() {
return $_SERVER['PHP_SELF'];
}
//上一页
private function pre_page() {
if ($this->page_id() == 1) { //页数等于1
return "<a href=".$this->php_self()."?page_id=1".$this->url().">上一页</a> ";
}elseif ($this->page_id() != 1) { //页数不等于1
return "<a href=".$this->php_self()."?page_id=".($this->page_id()-1).$this->url().">上一页</a> ";
}
}
//显示分页
private function display_page() {
$display_page = "";
if($this->page_num() <= 10){ //小于10页
for ($i=1;$i<=$this->page_num();$i++) //循环显示出页面
$display_page .= "<a href=".$this->php_self()."?page_id=".$i.$this->url().">".$i."</a> ";
return $display_page;
}elseif($this->page_num() > 10){ //大于10页
if($this->page_id() <= 6){
for ($i=1;$i<=10;$i++) //循环显示出页面
$display_page .= "<a href=".$this->php_self()."?page_id=".$i.$this->url().">".$i."</a> ";
return $display_page;
}elseif(($this->page_id() > 6) && ($this->page_num()-$this->page_id() >= 4)){
for ($i=$this->page_id()-5;$i<=$this->page_id()+4;$i++) //循环显示出页面
$display_page .= "<a href=".$this->php_self()."?page_id=".$i.$this->url().">".$i."</a> ";
return $display_page;
}elseif(($this->page_id() > 6) && ($this->page_num()-$this->page_id() < 4)){
for ($i=$this->page_num()-9;$i<=$this->page_num();$i++) //循环显示出页面
$display_page .= "<a href=".$this->php_self()."?page_id=".$i.$this->url().">".$i."</a> ";
return $display_page;
}
}
}
//下一页
private function next_page() {
if ($this->page_id() < $this->page_num()) { //页数小于总页数
return "<a href=".$this->php_self()."?page_id=".($this->page_id()+1).$this->url().">下一页</a> ";
}elseif ($this->page_id() == $this->page_num()) { //页数等于总页数
return "<a href=".$this->php_self()."?page_id=".$this->page_num().$this->url().">下一页</a> ";
}
}
// 设置分页信息
public function set_page_info() {
$page_info = "共".$this->datanum."条 ";
$page_info .= "<a href=".$this->php_self()."?page_id=1".$this->url().">首页</a> ";
$page_info .= $this->pre_page();
$page_info .= $this->display_page();
$page_info .= $this->next_page();
$page_info .= "<a href=".$this->php_self()."?page_id=".$this->page_num().$this->url().">尾页</a> ";
$page_info .= "第".$this->page_id()."/".$this->page_num()."页";
return $page_info;
}
}
?>2. Script 2:
<?php
//类的用法
// 读取分页类
include("pager.class.php");
// 数据库连接初始化
// $db = new mysql();
$impeach_host = '10.81.43.139';
$impeach_usr = 'vmtest15';
$impeach_passwd = 'vmtest15';
$impeach_name = 'ufeature';
$impeach_con = mysql_connect($impeach_host, $impeach_usr, $impeach_passwd) or
die("Can't connect ".mysql_error());
mysql_select_db($impeach_name, $impeach_con);
// 这是一个sql查询语句,并得到查询结果
$sql = "select word from ufeature.spam_accuse_word_list where flag='0'";
// 分页初始化
$page = new pager($sql,20);
// 20是每页显示的数量
// $res_1 = mysql_query($sql) or
// die("Can't get result ".mysql_error());
$result=mysql_query($page->sqlquery());
while($info = mysql_fetch_array($result,MYSQL_ASSOC)){
// while($info = mysql_fetch_array($res_1, MYSQL_ASSOC)){
echo $info["word"]."<br/>";
}
// 页码索引条
echo $page->set_page_info();
?>Method 2: Using ajax
1. First understand the usage of limit in the SQL statement
SELECT * FROM table...limit starting position, number of operations (the starting position starts from 0)
Example
Get the first 20 records: SELECT * FROM table...limit 0, 20
Get 20 records starting from the 11th one: SELECT * FROM table... limit 10, 20
LIMIT n is equivalent to LIMIT 0,n.
Such as select * from table LIMIT 5; //Return the first 5 rows, the same as select * from table LIMIT 0, 5
2. Paging principle
The so-called paging display , that is to say, the result set in the database is displayed section by section.
How to segment, what paragraph is it currently in (how many items per page, what page is it currently on)
Top 10 Records: select * from table limit 0,10
Records 11 to 20: select * from table limit 10,10
Records 21 to 30: select * from table limit 20,10
Paging formula:
(current page number - 1) 1) * $PageSize, $PageSize
3, $_SERVER["REQUEST_URI"] function
is a type of predefined server variable. All those starting with $_SERVER are called predetermined server variables.
The function of REQUEST_URI is to obtain the current URI, which is the complete address path except the domain name.
Example:
The current page is: http://www.test.com/home.php?id=23&cid=22
echo $_SERVER["REQUEST_URI"]
The result is:/home. php?id=23&cid=22
4. parse_url() parsing URL function
parse_url() is a function that parses URL into an array with fixed key values
Example
$ua=parse_url("http://username:password@hostname/path?arg=value#anchor");
print_r($ua);Result:
Array ( [scheme] => http ;协议 [host] => hostname ;主机域名 [user] => username ;用户 [pass] => password ;密码 [path] => /path ;路径 [query] => arg=value ;取参数 [fragment] => anchor ; )
5. Code example
This page for a message is divided into 3 parts, one is database design, and the other is One is the connection page and the other is the display page.
(1) Design database
The design database is named bbs. There is a data table called message, which contains fields such as title, lastdate, user, and content, which respectively represent the message title, message date, and so on. Message person, message content
(2) Connect page
<?php
$conn = @ mysql_connect("localhost", "root", "123456") or die("数据库链接错误");
mysql_select_db("bbs", $conn);
mysql_query("set names 'GBK'"); //使用GBK中文编码;
//将空格,换行转换为HTML可解析
function htmtocode($content) {
$content = str_replace("\n", "<br>", str_replace(" ", " ", $content)); //两个str_replace嵌套
return $content;
}
//$content=str_replace("'","‘",$content);
//htmlspecialchars();
?>(3) Display page
<?php
include("conn.php");
$pagesize=2; //设置每页显示2个记录
$url=$_SERVER["REQUEST_URI"];
$url=parse_url($url);
$url=$url[path];
$numq=mysql_query("SELECT * FROM `message`");
$num = mysql_num_rows($numq);
if($_GET){
$pageval=$_GET;
$page=($pageval-1)*$pagesize;
$page.=',';
}
if($num > $pagesize){
if($pageval<=1)$pageval=1;
echo "共 $num 条".
" <a href=$url?page=".($pageval-1).">上一页</a> <a href=$url?page=".($pageval+1).">下一页</a>";
}
$SQL="SELECT * FROM `message` limit $page $pagesize ";
$query=mysql_query($SQL);
while($row=mysql_fetch_array($query)){
?>
<table width=500 border="0" cellpadding="5" cellspacing="1" bgcolor="#add3ef">
<tr bgcolor="#eff3ff">
<td>标题:<?php echo $row[title]?></td> <td>时间:<?php echo $row[lastdate]?></td>
</tr>
<tr bgcolor="#eff3ff">
<td> 用户:<?php echo $row[user]?></td><td></td>
</tr>
<tr>
<td>内容:<?php echo htmtocode($row[content]);?></td>
</tr>
<br>
</table>
<?php
}
?>Method 3:
<script>
function viewpage(p){
if(window.XMLHttpRequest){
var xmlReq = new XMLHttpRequest();
} else if(window.ActiveXObject) {
var xmlReq = new ActiveXObject('Microsoft.XMLHTTP');
}
var formData = "page="+p;
xmlReq.onreadystatechange = function(){
if(xmlReq.readyState == 4){
document.getElementByIdx_x('content2').innerHTML = xmlReq.responseText;
}
}
xmlReq.open("post", "hotel_list.php", true);
xmlReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlReq.send(formData);
return false;
}
</script>Script 2:
header("Content-Type:text/html;charset=GB2312");
$pagesize=10;
//echo $_POST['page'];
$result = mysql_query("Select count(DISTINCT hotelname) FROM ".TBL_HOTELS);
$myrow = mysql_fetch_array($result);
$numrows=$myrow[0];
$pages=intval($numrows/$pagesize);
if ($numrows%$pagesize)
$pages++;
if (isset($_POST['page'])){
$page=intval($_POST['page']);
}
else{
//设置为第一页
$page=1;
}
$first=1;
$prev=$page-1;
$next=$page+1;
$last=$pages;
//计算记录偏移量
$offset=$pagesize*($page - 1);
//读取指定记录数
$result=mysql_query("select `hotelname` , count( * ) from ".TBL_HOTELS." GROUP BY `hotelname` order by id desc limit $offset,$pagesize");
$num = mysql_num_rows($result);
while ($row = mysql_fetch_array($result,MYSQL_NUM)) {
$hotelname[] = $row[0];
$countpeople[] = $row[1];
}
for($a=0;$a<$num;$a++)
{
//$result=mysql_query("select count(title) from " . TBL_Comments ." where `title`=\"".$title[$a]."\"");
//$row = mysql_fetch_row($result);
echo "<TABLE style=\"MARGIN-BOTTOM: 20px\" cellSpacing=0 cellPadding=0 width=100% border=0>\n";
echo "<TBODY>\n";
echo "<TR>\n";
echo "<TD style=\"PADDING-TOP: 5px\" vAlign=top align=left width=80>\n";
//rating_bar($title[$a],5);
echo "</TD>\n";
echo "<TD style=\"PADDING-TOP: 5px\" align=left width=100%><A title=$hotelname[$a] style=\"FONT-SIZE: 14px\" href=#>$hotelname[$a]</A>\n";
echo "</TD></TR>\n";
echo " <TR>\n";
echo "<TD></TD>\n";
echo "<TD style=\"PADDING-LEFT: 0px\">\n";
echo "<IMG src=\"images/comment.gif\" border=0> 推荐人数:($countpeople[$a]) |\n";
echo "<SPAN>平均分:<STRONG></STRONG> (".$count."票) | 评论数:()</SPAN>\n";
echo "</TD></TR></TBODY></TABLE>\n";
}
echo "<TABLE style=\"MARGIN-TOP: 30px\" cellSpacing=0 cellPadding=0 width=\"100%\"";
echo "border=0>";
echo "<TBODY><TR><TD colSpan=3 height=20>";
echo "<DIV align=center>";
echo "<P align=left><FONT color=red>第".$page."页/总".$pages."页 | 总".$numrows."条</FONT> | ";
if ($page>1) echo "<a onclick=\"viewpage(".$first.")\" href='#'>首页</a> | ";
if ($page>1) echo "<a onclick=\"viewpage(".$prev.")\" href='#'>上页</a> | ";
if ($page<$pages) echo "<a onclick=\"viewpage(".$next.")\" href='#'>下页</a> | ";
if ($page<$pages) echo "<a onclick=\"viewpage(".$last.")\" href='#'>尾页</a>";
echo "转到第 <INPUT maxLength=3 size=3 value=1 name=goto_page> 页 <INPUT hideFocus onclick=\"viewpage(document.all.goto_page.value)\" type=button value=Go name=cmd_goto>";
echo "</P></DIV></TD></TR></TBODY></TABLE>";Recommended learning: "
PHP Video TutorialThe above is the detailed content of How to write paging query in php. For more information, please follow other related articles on the PHP Chinese website!
ACID vs BASE Database: Differences and when to use each.Mar 26, 2025 pm 04:19 PMThe article compares ACID and BASE database models, detailing their characteristics and appropriate use cases. ACID prioritizes data integrity and consistency, suitable for financial and e-commerce applications, while BASE focuses on availability and
PHP Secure File Uploads: Preventing file-related vulnerabilities.Mar 26, 2025 pm 04:18 PMThe article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.
PHP Input Validation: Best practices.Mar 26, 2025 pm 04:17 PMArticle discusses best practices for PHP input validation to enhance security, focusing on techniques like using built-in functions, whitelist approach, and server-side validation.
PHP API Rate Limiting: Implementation strategies.Mar 26, 2025 pm 04:16 PMThe article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand
PHP Password Hashing: password_hash and password_verify.Mar 26, 2025 pm 04:15 PMThe article discusses the benefits of using password_hash and password_verify in PHP for securing passwords. The main argument is that these functions enhance password protection through automatic salt generation, strong hashing algorithms, and secur
OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.Mar 26, 2025 pm 04:13 PMThe article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.
PHP XSS Prevention: How to protect against XSS.Mar 26, 2025 pm 04:12 PMThe article discusses strategies to prevent XSS attacks in PHP, focusing on input sanitization, output encoding, and using security-enhancing libraries and frameworks.
PHP Interface vs Abstract Class: When to use each.Mar 26, 2025 pm 04:11 PMThe article discusses the use of interfaces and abstract classes in PHP, focusing on when to use each. Interfaces define a contract without implementation, suitable for unrelated classes and multiple inheritance. Abstract classes provide common funct


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

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

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

WebStorm Mac version
Useful JavaScript development tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft






