Home Backend Development PHP Tutorial Practical simple PHP paging collection including usage methods_PHP tutorial

Practical simple PHP paging collection including usage methods_PHP tutorial

Jul 13, 2016 am 10:26 AM
php pagination

Method 1:

Copy the code The code is as follows:

/*
The paging class is used to display multiple pieces of data in pages
version: 1.0
Date: 2013-10-20
*/

/*
The call is very convenient. First connect to the database and directly pass the sql string to be queried. You can also specify the number of data displayed on each page
For example $pages = new Page( 'SELECT * FROM `zy_common_member`');
or $pages = new Page('SELECT * FROM `zy_common_member`', 10);
*/
class Page{
private $curPage;
private $totalPages;//How many pages of data are displayed in total
private $dispNum;//Number of data items displayed on each page
private $queryStr;//SQL statement for query
private $limitStr ; // Query the Limit control statement behind the sentence

/ *
The constructor
$ Querystr query data SQL statement
$ Dispnum The number of data displayed by each page
*/ */
public function __construct($queryStr='',$dispNum=10){
$result = mysql_query($queryStr);
$totalNum = mysql_num_rows($result);
$this-> ;dispNum = $dispNum;
$this->totalPages = ceil($totalNum / $dispNum);
$this->queryStr = $queryStr;

$temp = (isset( $_GET["curPage"]) ? $_GET["curPage"] : 1);
$this->setCurPage($temp);

$this->showCurPage();
$this->showFoot();
}

/*Display the data content of the current page*/
private function showCurPage(){
$this ->limitStr = ' LIMIT '.(($this->curPage - 1)* $this->dispNum).','.$this->dispNum;
                                                                                                                            ->limitStr;
                   $result = mysql_query($this->queryStr.$this->limitStr);                                                                        🎜> if ($ this->totalPages > 0)
                                                                                             else
{
'
';
                                                                                                                                        
            $cols = mysql_num_fields($result);

            echo '';
            echo '';
            for($i=0; $i<$cols; $i++)
            {
                echo '';
            }
            echo '';

            while($row = mysql_fetch_assoc($result))
            {
                echo '';
                foreach($row as $key=>$value)
                {
                    echo '';
                }
                echo '';
            }

            echo '
';
                echo mysql_field_name($result, $i);
                echo '
';
                    echo $value;
                    echo '
';
        }

        private function setCurPage($curPage){
                if($curPage < 1)
                {
                    $curPage = 1;
                }
                else if($curPage > $this->totalPages)
                {
                    $curPage = $this->totalPages;
                }
                    $this->curPage = $curPage;
        }

        /*
        显示分页页脚的信息
        如首页,上一页,下一页,尾页等信息
        */
        private function showFoot(){
            echo '首页';
            echo '上一页';
            echo '下一页';
            echo '尾页';
        }

  }

?>


方法二:

复制代码 代码如下:

class mysqlPager{
var $pagePerNum=5;//Number of data items displayed on each page
var $pagePerGroup=5;//Number of pages in each paging group
var $curPage=0;//Current page, Defualt first page
var $totalPage=0;//Total number of pages
var $totalNum=0;//Total number of data items
var $curPageGroup=0;//Current paging group
var $curPageUrl="";//Currently used paging URL
var $custom;//Custom style
var $pageQuerySql= "";
function mysqlPager(){//Constructor PHP4
}
/**
* Initialize all variables
*/
function InitAllVar($totalNum,$pagePerGroup,$curPageUrl,$curPage=1 ,$curPageGroup=1)
{
$this->totalNum=$totalNum;
$this->pagePerGroup=$pagePerGroup;
$this->curPageUrl=$curPageUrl;
$this->curPage=$curPage;
$this->curPageGroup=$curPageGroup;
}
/**
* Set the current page variable
*
* @param number $curPage
*/
function setCurPage($curPage)
{
$this->curPage=$curPage;
}
/**
* Set the current paging group variable
*
* @param mixed $curPageGroup
*/
function setCurPageGroup($curPageGroup)
{
$this- >curPageGroup=$curPageGroup;
}
/**
* Set the URL of the currently used distribution class
* $curPageUrl string
*/
function setCurPageUrl($curPageUrl)
{
$this->curPageUrl=$curPageUrl;
}
/**
* Get all
*
* @param number $totalNum
* @param number $curPage
* @return float
*/
function getTotalPage($totalNum,$curPage=0)
{
return $this->totalPage=ceil($totalNum/$this- >pagePerNum);
}
/**
* Set user-defined style
*
* @param mixed $customStyle
*/
function setCustomStyle($customStyle)
{
$this->customStyle=$customStyle;
}
/**
* Set user-defined style return string
*
*
* @param mixed $pagerString
*/
function setCustomStyleString($pagerString)
{
return $styleString="".$pagerString. "";
}
/**
* You can output navigation page information without parameters, but you must set the corresponding variables before use
*
* @param mixed $curPageGroup
* @param mixed $curPage
* @param mixed $curPageUrl
*/
function showNavPager($curPageGroup=0,$curPage=0,$curPageUrl=0)
{
if($curPageGroup)
{
$this->curPageGroup=$curPageGroup;
}
if($curPage)
{
$this->curPage=$ curPage;
}
if($curPageUrl)
{
$this->curPageUrl=$curPageUrl;
}
$rtnString="";
//Judgement Whether the variable is initialized
if($this->curPageGroup && $this->curPageUrl && $this->totalNum && $this->curPage)
{
$this-> totalPage=$this->getTotalPage($this->totalNum);
if($this->curPage==1)
$this->curPage=($this->curPageGroup- 1)*$this->pagePerGroup+1;
if($this->curPageGroup!=1)
{
$prePageGroup=$this->curPageGroup-1;
$ rtnString.="".$this->setCustomStyleString("<<")." " ;
}
for($i=1;$i<=$this->pagePerGroup;$i++)
{
$curPageNum=($this->curPageGroup-1)* $this->pagePerGroup+$i;
if($curPageNum<=$this->totalPage){
if($curPageNum==$this->curPage)
{
$ rtnString.=" ".$this->setCustomStyleString($curPageNum);
}else
{
$rtnString.=" curPageUrl?cpg={$ this->curPageGroup}&cp=$curPageNum >";
$rtnString.=$this->setCustomStyleString($curPageNum)."
";
}
}
}
if($this->curPageGrouptotalPage/$this->pagePerGroup)-1)
{
$nextPageGroup=$this->curPageGroup+ 1;
$rtnString.=" curPageUrl?cpg=$nextPageGroup >".$this->setCustomStyleString(">>")."}
$this->pageQuerySql=" limit ".(($this->curPage-1)*$this->pagePerNum).",".$this-> pagePerNum;
}
else
{
$rtnString="Error: Variable not initialized! ";
}
return $rtnString;
}
/**
* Get the complete Sql statement for querying MYSQL
*
* @param mixed $sql
*/
function getQuerySqlStr($sql)
{
$allsql=$sql. $this->pageQuerySql;
return $allsql;
}
/**
* Set how many data items there are on each page
*
* @param INT $num
*/
function setPagePerNum($num)
{
$this-> pagePerNum=$num;
}
}
?>

Usage:
$curPage=$_GET['cp'];
$curPageGroup=$_GET['cpg']
if($curPage=="")
$curPage =1;
if($curPageGroup=="")
$curPageGroup=1;
//They all start from 1. The incoming data must be verified before to prevent injection
/ /. . .
$pager=new MysqlPager();
$pager->initAllVar(...)
$pager->showNavPager();
//The following SQL can be any output
$sql="select id form dbname ";
$querysql=$pager->getQuerySqlStr($sql)
//You can use $querysql to query the database in the future to get the corresponding result set


Method three:

PHP paging function:

Copy code The code is as follows:

< ?
//In order to avoid duplication Including files causes errors,
adds a condition to determine whether the function exists:
if(!function_exists(pageft)){
//Define the function pageft(), the meaning of the three parameters is:
//$totle: the total number of information;
//$displaypg: the number of information displayed on each page, the default setting here is 20;
//$url: the link in the paging navigation, in addition to adding different query information
The parts outside "page" are the same as this URL.
//The default value should be set to the URL of this page (i.e. $_SERVER["REQUEST_URI"])
, but the right side of the default value can only be a constant, so the default value is set to an empty string
, and then set it to the URL of this page inside the function.
function pageft($totle,$displaypg=20,$url=”){
//Define several global variables:
//$page: current page number;
//$firstcount: (Database) starting item of query;
//$pagenav: page navigation bar code, it is not output inside the function;
//$_SERVER: Read the URL of this page "$_SERVER["REQUEST_URI" ]" required.
global $page,$firstcount,$pagenav,$_SERVER;
//In order to make the "$displaypg" here accessible from outside the function,
set it as a global variable. Note that after a variable is redefined
as a global variable, the original value is overwritten, so reassign it here
$GLOBALS["displaypg"]=$displaypg;
if(!$page) $. page=1;
//If $url uses the default value, which is an empty value, the value is assigned to the URL of this page:
if(!$url){ $url=$_SERVER["REQUEST_URI"];}
//URL analysis:
$parse_urlparse_url=parse_url($url);
$url_query=$parse_url["query"];
//Take out the query string of the URL separately
if($ url_query){
//Because the URL may contain page number information, we need to remove it
in order to add new page number information.
//Regular expressions are used here, please refer to "PHP. Regular expression "
$url_query=ereg_replace("(^|&)page=$page","",$url_query);

//Replace the query string of the processed URL The query string of the original URL:
$url=str_replace($parse_url["query"],$url_query,$url);

//Add page query information after the URL, but wait for assignment :
if($url_query) $url.=”&page”; else $url.=”page”;
}else {
$url.=”?page”;
}
$lastpg=ceil($totle/$displaypg);
//The last page is also the total number of pages
$page=min($lastpg,$page);
$prepg=$page-1 ;
//Previous page
$nextpg=($page==$lastpg ? 0 : $page+1);
//Next page
$firstcount=($page-1 )*$displaypg;
//Start paging navigation bar code:
$pagenav=”Display the < B>”.($totle?($firstcount+1):0).”
< ; /B>-< B>”.min($firstcount+$displaypg,$totle).”
< /B> records, total $totle records< BR>”;
// If there is only one page, jump out of the function:
if($lastpg<=1) return false;
$pagenav.=” < a href='$url=1′>Homepage< /a> “ ;
if($prepg) $pagenav.=” < a href='$url=$prepg'>
Previous page< /a> “; else $pagenav.=” Previous page”;
if($nextpg) $pagenav.=” < a href='$url=$nextpg'>
Next page< /a> “; else $pagenav.=”Next page”;
$pagenav.=” < a href='$url=$lastpg'>Last page< /a> “;
//Drop-down jump list, loop through all page numbers:
$ pagenav.=”Go to page< select name=’topage’
size=’1′ onchange=’window.location=”
$url=”+this.value'>n”;
for($i=1;$i< =$lastpg;$i++){
if($i==$page) $pagenav.=”< option value='$i'
selected>$ i< /option>n”;
else $pagenav.=”< option value=’$i’>$i< /option>n”; ; /select> page of $lastpg";
}
}
?>

The pageft() function is called during paging. However, it does not output anything, but generates several global variables for use: $firstcount, $displaypg, $pagenav.
The following is an example of how to use the PHP paging function:

Copy the code The code is as follows:

< ?
//(The previous procedure is omitted)
include("pageft.php");
//Include the "pageft.php" file
//Get the total number of information
$result=mysql_query("select
* from mytable”);
$total=mysql_num_rows($result);
//Call pageft() to display 10 pieces of information per page
(When using the default 20, you can omit this parameters),
use this page URL (default, so omitted).
pageft($total,10);
//The global variables generated now come in handy:
$result=mysql_query(”select *
from mytable limit $firstcount,
$displaypg “);
while($row=mysql_fetch_array($result)){
//(list content omitted)
}
//Output paging navigation bar code:
echo $ pagenav;
//(The following procedures are omitted)
?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/824886.htmlTechArticleMethod 1: Copy the code as follows: ?php /* The paging class is used to display versions of multiple pieces of data in paging :1.0 Date: 2013-10-20 */ /* The call is very convenient, just connect to the database first, then...
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

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.

Undress AI Tool

Undress AI Tool

Undress images for free

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)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

See all articles