国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home Backend Development PHP Problem There are several ways to implement paging in php

There are several ways to implement paging in php

Sep 15, 2021 am 10:29 AM
php Pagination

There are three ways to implement paging in php, which are: 1. Paging sql queries through functions such as "mysql_query"; 2. Using ajax to achieve paging; 3. Through "function viewpage(p){ ...}" script implements paging.

There are several ways to implement paging in php

The operating environment of this article: windows7 system, PHP7.1 version, DELL G3 computer

How many methods are there to implement paging in php?

3 ways to implement paging function in php

Go directly to the code, I hope you will read it carefully.

Method 1: To perform paging using sql query, you need to call several functions. See the script for details:
1.pager.class.php

<?php
  
  class pager {
    public $sql; //SQL查詢語句
    public $datanum; //查詢所有的數(shù)據(jù)總記錄數(shù)
    public $page_size; //每頁顯示記錄的條數(shù)
    protected $_errstr;
    protected $_conn;
    protected $_query_id;

    public function query($query)///這個函數(shù)有問題,暫時可以不用
    {
    $ret = false;
    if (!empty($query)) {
      if ($this->_conn === false || !is_resource($this->_conn)) {
       warningLog(__METHOD__ . &#39;: query sql with no connection&#39;, 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 = &#39;SUCCESS&#39;;
    $ret = $this->_query_id;
      }
    }
     $msg = ($ret === false) ? &#39;false&#39; : 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;
    }

    //當(dāng)前頁數(shù)
    public function page_id() {
      if($_SERVER[&#39;QUERY_STRING&#39;] == ""){
        return 1;
      }elseif(substr_count($_SERVER[&#39;QUERY_STRING&#39;],"page_id=") == 0){
        return 1;
      }else{
        return intval(substr($_SERVER[&#39;QUERY_STRING&#39;],8));
      }
    }

    //剩余url值
    public function url() {
      if($_SERVER[&#39;QUERY_STRING&#39;] == ""){
        return "";
      }elseif(substr_count($_SERVER[&#39;QUERY_STRING&#39;],"page_id=") == 0){
        return "&".$_SERVER[&#39;QUERY_STRING&#39;];
      }else{
        return str_replace("page_id=".$this->page_id(),"",$_SERVER[&#39;QUERY_STRING&#39;]);
      }
    }

    //總頁數(shù)
    public function page_num() {
      if($this->datanum == 0){
        return 1;
      }else{
        return ceil($this->datanum/$this->page_size);
      }
    }
//數(shù)據(jù)庫查詢的偏移量
    public function start() {
      return ($this->page_id()-1)*$this->page_size;
    }

    //數(shù)據(jù)輸出
    public function sqlquery() {
      return $this->sql." limit ".$this->start().",".$this->page_size;
    }

    //獲取當(dāng)前文件名
    private function php_self() {
      return $_SERVER[&#39;PHP_SELF&#39;];
    }

    //上一頁
    private function pre_page() {
      if ($this->page_id() == 1) { //頁數(shù)等于1
        return "<a href=".$this->php_self()."?page_id=1".$this->url().">上一頁</a> ";
      }elseif ($this->page_id() != 1) { //頁數(shù)不等于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++) //循環(huán)顯示出頁面
          $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++) //循環(huán)顯示出頁面
            $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++) //循環(huán)顯示出頁面
            $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++) //循環(huán)顯示出頁面
            $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()) { //頁數(shù)小于總頁數(shù)
        return "<a href=".$this->php_self()."?page_id=".($this->page_id()+1).$this->url().">下一頁</a> ";
      }elseif ($this->page_id() == $this->page_num()) { //頁數(shù)等于總頁數(shù)
        return "<a href=".$this->php_self()."?page_id=".$this->page_num().$this->url().">下一頁</a> ";
      }
    }

    // 設(shè)置分頁信息
    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");
  // 數(shù)據(jù)庫連接初始化
//  $db = new mysql();
  $impeach_host = &#39;10.81.43.139&#39;;
  $impeach_usr = &#39;vmtest15&#39;;
  $impeach_passwd = &#39;vmtest15&#39;;
  $impeach_name = &#39;ufeature&#39;;
  $impeach_con = mysql_connect($impeach_host, $impeach_usr, $impeach_passwd) or
    die("Can&#39;t connect ".mysql_error());
  mysql_select_db($impeach_name, $impeach_con);
  // 這是一個sql查詢語句,并得到查詢結(jié)果
  $sql = "select word from ufeature.spam_accuse_word_list where flag=&#39;0&#39;";
  // 分頁初始化
  $page = new pager($sql,20);
  // 20是每頁顯示的數(shù)量
  // $res_1 = mysql_query($sql) or
  //    die("Can&#39;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 SQL statements

SELECT * FROM table …… limit 開始位置 , 操作條數(shù) (其中開始位置是從0開始的)

Example
Take the first 20 items Records: SELECT * FROM table ...... limit 0, 20
Take 20 records starting from the 11th: 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, is the same as select * from table LIMIT 0, 5
2 , Paging principle

The so-called paging display means that the result set in the database is displayed segment by segment. Page)
The first 10 records:
select * from table limit 0,10
The 11th to 20th records:
select * from table limit 10,10
Records 21 to 30:
select * from table limit 20,10
Paging formula: (current page number - 1) Number, number of items per page

Select * from table limit ($Page- 1) * $PageSize, $PageSize

3, $_SERVER["REQUEST_URI"] function
A type of predefined server variable, all 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 behind it 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  ;協(xié)議
 [host] => hostname  ;主機(jī)域名
 [user] => username  ;用戶
 [pass] => password  ;密碼
 [path] => /path   ;路徑
 [query] => arg=value  ;取參數(shù)
 [fragment] => anchor  ;
)

5. Code example
This paging for a message is divided into three parts, one is the database design, 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("數(shù)據(jù)庫鏈接錯誤");
mysql_select_db("bbs", $conn);
mysql_query("set names &#39;GBK&#39;"); //使用GBK中文編碼;
//將空格,換行轉(zhuǎn)換為HTML可解析
function htmtocode($content) {
 $content = str_replace("\n", "<br>", str_replace(" ", " ", $content)); //兩個str_replace嵌套
 return $content;
}
//$content=str_replace("&#39;","‘",$content);
 //htmlspecialchars();
 
?>

(3) Display page

<?php
 include("conn.php");
$pagesize=2; //設(shè)置每頁顯示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.=&#39;,&#39;;
}
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>標(biāo)題:<?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>內(nèi)容:<?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(&#39;Microsoft.XMLHTTP&#39;); 
} 
var formData = "page="+p; 
xmlReq.onreadystatechange = function(){ 
if(xmlReq.readyState == 4){ 
document.getElementByIdx_x(&#39;content2&#39;).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[&#39;page&#39;]; 
$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[&#39;page&#39;])){ 
$page=intval($_POST[&#39;page&#39;]); 
} 
else{ 
//設(shè)置為第一頁 
$page=1; 
} 
$first=1; 
$prev=$page-1; 
$next=$page+1; 
$last=$pages; 
//計算記錄偏移量 
$offset=$pagesize*($page - 1); 
//讀取指定記錄數(shù) 
$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> 推薦人數(shù):($countpeople[$a]) |\n"; 
echo "<SPAN>平均分:<STRONG></STRONG> (".$count."票) | 評論數(shù):()</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 "<p align=center>"; 
echo "<P align=left><FONT color=red>第".$page."頁/總".$pages."頁 | 總".$numrows."條</FONT> | "; 
if ($page>1) echo "<a onclick=\"viewpage(".$first.")\" href=&#39;#&#39;>首頁</a> | "; 
if ($page>1) echo "<a onclick=\"viewpage(".$prev.")\" href=&#39;#&#39;>上頁</a> | "; 
if ($page<$pages) echo "<a onclick=\"viewpage(".$next.")\" href=&#39;#&#39;>下頁</a> | "; 
if ($page<$pages) echo "<a onclick=\"viewpage(".$last.")\" href=&#39;#&#39;>尾頁</a>"; 
echo "轉(zhuǎn)到第 <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></p></TD></TR></TBODY></TABLE>";
Recommended learning: "

PHP Video Tutorial"

The above is the detailed content of There are several ways to implement paging in php. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

A Simple Guide to PHP Setup A Simple Guide to PHP Setup Jul 18, 2025 am 04:25 AM

The key to setting up PHP is to clarify the installation method, configure php.ini, connect to the web server and enable necessary extensions. 1. Install PHP: Use apt for Linux, Homebrew for Mac, and XAMPP recommended for Windows; 2. Configure php.ini: Adjust error reports, upload restrictions, etc. and restart the server; 3. Use web server: Apache uses mod_php, Nginx uses PHP-FPM; 4. Install commonly used extensions: such as mysqli, json, mbstring, etc. to support full functions.

Tips for Writing PHP Comments Tips for Writing PHP Comments Jul 18, 2025 am 04:51 AM

The key to writing PHP comments is to clarify the purpose and specifications. Comments should explain "why" rather than "what was done", avoiding redundancy or too simplicity. 1. Use a unified format, such as docblock (/*/) for class and method descriptions to improve readability and tool compatibility; 2. Emphasize the reasons behind the logic, such as why JS jumps need to be output manually; 3. Add an overview description before complex code, describe the process in steps, and help understand the overall idea; 4. Use TODO and FIXME rationally to mark to-do items and problems to facilitate subsequent tracking and collaboration. Good annotations can reduce communication costs and improve code maintenance efficiency.

Writing Effective PHP Comments Writing Effective PHP Comments Jul 18, 2025 am 04:44 AM

Comments cannot be careless because they want to explain the reasons for the existence of the code rather than the functions, such as compatibility with old interfaces or third-party restrictions, otherwise people who read the code can only rely on guessing. The areas that must be commented include complex conditional judgments, special error handling logic, and temporary bypass restrictions. A more practical way to write comments is to select single-line comments or block comments based on the scene. Use document block comments to explain parameters and return values at the beginning of functions, classes, and files, and keep comments updated. For complex logic, you can add a line to the previous one to summarize the overall intention. At the same time, do not use comments to seal code, but use version control tools.

Learning PHP: A Beginner's Guide Learning PHP: A Beginner's Guide Jul 18, 2025 am 04:54 AM

TolearnPHPeffectively,startbysettingupalocalserverenvironmentusingtoolslikeXAMPPandacodeeditorlikeVSCode.1)InstallXAMPPforApache,MySQL,andPHP.2)Useacodeeditorforsyntaxsupport.3)TestyoursetupwithasimplePHPfile.Next,learnPHPbasicsincludingvariables,ech

Mastering PHP Block Comments Mastering PHP Block Comments Jul 18, 2025 am 04:35 AM

PHPblockcommentsareusefulforwritingmulti-lineexplanations,temporarilydisablingcode,andgeneratingdocumentation.Theyshouldnotbenestedorleftunclosed.BlockcommentshelpindocumentingfunctionswithPHPDoc,whichtoolslikePhpStormuseforauto-completionanderrorche

Improving Readability with Comments Improving Readability with Comments Jul 18, 2025 am 04:46 AM

The key to writing good comments is to explain "why" rather than just "what was done" to improve the readability of the code. 1. Comments should explain logical reasons, such as considerations behind value selection or processing; 2. Use paragraph annotations for complex logic to summarize the overall idea of functions or algorithms; 3. Regularly maintain comments to ensure consistency with the code, avoid misleading, and delete outdated content if necessary; 4. Synchronously check comments when reviewing the code, and record public logic through documents to reduce the burden of code comments.

Quick PHP Installation Tutorial Quick PHP Installation Tutorial Jul 18, 2025 am 04:52 AM

ToinstallPHPquickly,useXAMPPonWindowsorHomebrewonmacOS.1.OnWindows,downloadandinstallXAMPP,selectcomponents,startApache,andplacefilesinhtdocs.2.Alternatively,manuallyinstallPHPfromphp.netandsetupaserverlikeApache.3.OnmacOS,installHomebrew,thenrun'bre

Effective PHP Commenting Effective PHP Commenting Jul 18, 2025 am 04:33 AM

The key to writing PHP comments is clear, useful and concise. 1. Comments should explain the intention behind the code rather than just describing the code itself, such as explaining the logical purpose of complex conditional judgments; 2. Add comments to key scenarios such as magic values, old code compatibility, API interfaces, etc. to improve readability; 3. Avoid duplicate code content, keep it concise and specific, and use standard formats such as PHPDoc; 4. Comments should be updated synchronously with the code to ensure accuracy. Good comments should be thought from the perspective of others, reduce the cost of understanding, and become a code understanding navigation device.

See all articles