search
HomeBackend DevelopmentPHP Tutorial实用的简单PHP分页集合包括使用方法_php实例

方法一:

复制代码 代码如下:

    /*
    分页类 用于实现对多条数据分页显示 
    version:1.0
    Date:2013-10-20
    */

    /*
        调用非常方便,先连接好数据库,直接传人查询的sql字符串即可,也可以指定每页显示的数据条数
        例如$pages = new Page('SELECT * FROM `zy_common_member`');
        或  $pages = new Page('SELECT * FROM `zy_common_member`', 10);
    */
    class Page{
        private $curPage;
        private $totalPages;//数据总共分多少页显示
        private $dispNum;//每页显示的数据条数
        private $queryStr;//查询的SQL语句
        private $limitStr;//查询语句后面的limit控制语句

        /*
        构造函数
        $queryStr 查询数据的SQL语句
        $dispNum  每页显示的数据条数
        */
        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();
        }       

        /*显示当前页的数据内容*/
        private function showCurPage(){
            $this->limitStr = ' LIMIT '.(($this->curPage - 1)* $this->dispNum).','.$this->dispNum;
            //echo $this->queryStr.$this->limitStr;
            $result = mysql_query($this->queryStr.$this->limitStr);

            if (!$result)
            {           
                if ($this->totalPages > 0)
                {
                    echo '查询出错'.'
';
                }
                else
                {
                    echo '无数据'.'
';
                }
                return;
            }
            $cols = mysql_num_fields($result);

            echo '';
            echo '';
            for($i=0; $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                 {
                    $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;//每页显示数据项数
var $pagePerGroup=5;//每分页组中页数
var $curPage=0;//当前页,Defualt 第一页
var $totalPage=0;//总页数
var $totalNum=0;//数据项总数
var $curPageGroup=0;//当前分页组
var $curPageUrl="";//当前用到分页的 URL
var $custom;//自定义风格
var $pageQuerySql="";
function mysqlPager(){//构造函数 PHP4
}
/**
* 初始化所有变量
*/
function InitAllVar($totalNum,$pagePerGroup,$curPageUrl,$curPage=1,$curPageGroup=1)
{
$this->totalNum=$totalNum;
$this->pagePerGroup=$pagePerGroup;
$this->curPageUrl=$curPageUrl;
$this->curPage=$curPage;
$this->curPageGroup=$curPageGroup;
}
/**
* 设置当前页变量
*
* @param 数字 $curPage
*/
function setCurPage($curPage)
{
$this->curPage=$curPage;
}
/**
* 设置当前分页组变量
*
* @param mixed $curPageGroup
*/
function setCurPageGroup($curPageGroup)
{
$this->curPageGroup=$curPageGroup;
}
/**
* 设置当前用到分布类的URL
* $curPageUrl string
*/
function setCurPageUrl($curPageUrl)
{
$this->curPageUrl=$curPageUrl;
}
/**
* 获取所有
*
* @param 数字 $totalNum
* @param 数字 $curPage
* @return float
*/
function getTotalPage($totalNum,$curPage=0)
{
return $this->totalPage=ceil($totalNum/$this->pagePerNum);
}
/**
* 设置用户自定义风格
*
* @param mixed $customStyle
*/
function setCustomStyle($customStyle)
{
$this->customStyle=$customStyle;
}
/**
* 设置用户自定义风格返回字符串
*
*
* @param mixed $pagerString
*/
function setCustomStyleString($pagerString)
{
return $styleString="".$pagerString."";
}
/**
* 输出导航页信息 可以不用参数,但是在使用前一定要设置相应的变量
*
* @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="";
//判断变量是否以经初始化
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;$ipagePerGroup;$i++)
{
$curPageNum=($this->curPageGroup-1)*$this->pagePerGroup+$i;
if($curPageNumtotalPage){
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="错误:变量未初始化!";
}
return $rtnString;
}
/**
* 得到完整的查询MYSQL的Sql语句
*
* @param mixed $sql
*/
function getQuerySqlStr($sql)
{
$allsql=$sql.$this->pageQuerySql;
return $allsql;
}
/**
* 设置每页有多少数据项
*
* @param INT $num
*/
function setPagePerNum($num)
{
$this->pagePerNum=$num;
}
}
?>

使用方法:
$curPage=$_GET['cp'];
$curPageGroup=$_GET['cpg']
if($curPage=="")
$curPage=1;
if($curPageGroup=="")
$curPageGroup=1;
//都是从1开始,之前要对传入的数据进行验证,防注入
//。。。
$pager=new MysqlPager();
$pager->initAllVar(...)
$pager->showNavPager();
//后面的SQL可以是任意的输出
$sql="select id form dbname ";
$querysql=$pager->getQuerySqlStr($sql)
//以后用$querysql 查询数据库就可以得到相应的结果集了


方法三:

PHP分页函数:

复制代码 代码如下:

//为了避免重复包含文件而造成错误,
加了判断函数是否存在的条件: 
if(!function_exists(pageft)){ 
//定义函数pageft(),三个参数的含义为: 
//$totle:信息总数; 
//$displaypg:每页显示信息数,这里设置为默认是20; 
//$url:分页导航中的链接,除了加入不同的查询信息
“page”外的部分都与这个URL相同。 
//默认值本该设为本页URL(即$_SERVER["REQUEST_URI"])
,但设置默认值的右边只能为常量,所以该默认值设为空字符串
,在函数内部再设置为本页URL。 
function pageft($totle,$displaypg=20,$url=”){ 
//定义几个全局变量: 
//$page:当前页码; 
//$firstcount:(数据库)查询的起始项; 
//$pagenav:页面导航条代码,函数内部并没有将它输出; 
//$_SERVER:读取本页URL“$_SERVER["REQUEST_URI"]”所必须。 
global $page,$firstcount,$pagenav,$_SERVER; 
//为使函数外部可以访问这里的“$displaypg”,
将它也设为全局变量。注意一个变量重新定
义为全局变量后,原值被覆盖,所以这里给它重新赋值。 
$GLOBALS["displaypg"]=$displaypg; 
if(!$page) $page=1; 
//如果$url使用默认,即空值,则赋值为本页URL: 
if(!$url){ $url=$_SERVER["REQUEST_URI"];} 
//URL分析: 
$parse_urlparse_url=parse_url($url); 
$url_query=$parse_url["query"];
//单独取出URL的查询字串 
if($url_query){ 
//因为URL中可能包含了页码信息,我们要把它去掉,
以便加入新的页码信息。 
//这里用到了正则表达式,请参考“PHP中的正规表达式”
$url_query=ereg_replace(”(^|&)page=$page”,”",$url_query); 

//将处理后的URL的查询字串替换原来的URL的查询字串: 
$url=str_replace($parse_url["query"],$url_query,$url); 

//在URL后加page查询信息,但待赋值: 
if($url_query) $url.=”&page”; else $url.=”page”; 
}else { 
$url.=”?page”; 
}
$lastpg=ceil($totle/$displaypg);  
//最后页,也是总页数 
$page=min($lastpg,$page); 
$prepg=$page-1;  
//上一页 
$nextpg=($page==$lastpg ? 0 : $page+1);  
//下一页 
$firstcount=($page-1)*$displaypg; 
//开始分页导航条代码: 
$pagenav=”显示第 ”.($totle?($firstcount+1):0).”
-”.min($firstcount+$displaypg,$totle).”
条记录,共 $totle 条记录”; 
//如果只有一页则跳出函数: 
if($lastpg$pagenav.=” 首页 “; 
if($prepg) $pagenav.=”
前页 “; else $pagenav.=” 前页 “; 
if($nextpg) $pagenav.=”
后页 “; else $pagenav.=” 后页 “; 
$pagenav.=” 尾页 “; 
//下拉跳转列表,循环列出所有页码: 
$pagenav.=” 到第 size='1′ onchange='window.location=\”
$url=\”+this.value'>\n”; 
for($i=1;$iif($i==$page) $pagenav.=” selected>$i\n”; 
else $pagenav.=”$i\n”; 

$pagenav.=” 页,共 $lastpg 页”; 


?>

分页时调用pageft()函数。不过它并没有输出任何东西,但产生几个全局变量供使用:$firstcount、$displaypg、$pagenav。
下面举例说明PHP分页函数的用法:

复制代码 代码如下:

//(前面程序略) 
include(”pageft.php”);
 //包含“pageft.php”文件 
//取得总信息数 
$result=mysql_query(”select
* from mytable”); 
$total=mysql_num_rows($result); 
//调用pageft(),每页显示10条信息
(使用默认的20时,可以省略此参数),
使用本页URL(默认,所以省略掉)。 
pageft($total,10); 
//现在产生的全局变量就派上用场了: 
$result=mysql_query(”select *
from mytable limit $firstcount,
$displaypg “); 
while($row=mysql_fetch_array($result)){ 
//(列表内容略) 

//输出分页导航条代码: 
echo $pagenav; 
//(后面程序略) 
?>
Statement
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
How can you check if a PHP session has already started?How can you check if a PHP session has already started?Apr 30, 2025 am 12:20 AM

In PHP, you can use session_status() or session_id() to check whether the session has started. 1) Use the session_status() function. If PHP_SESSION_ACTIVE is returned, the session has been started. 2) Use the session_id() function, if a non-empty string is returned, the session has been started. Both methods can effectively check the session state, and choosing which method to use depends on the PHP version and personal preferences.

Describe a scenario where using sessions is essential in a web application.Describe a scenario where using sessions is essential in a web application.Apr 30, 2025 am 12:16 AM

Sessionsarevitalinwebapplications,especiallyfore-commerceplatforms.Theymaintainuserdataacrossrequests,crucialforshoppingcarts,authentication,andpersonalization.InFlask,sessionscanbeimplementedusingsimplecodetomanageuserloginsanddatapersistence.

How can you manage concurrent session access in PHP?How can you manage concurrent session access in PHP?Apr 30, 2025 am 12:11 AM

Managing concurrent session access in PHP can be done by the following methods: 1. Use the database to store session data, 2. Use Redis or Memcached, 3. Implement a session locking strategy. These methods help ensure data consistency and improve concurrency performance.

What are the limitations of using PHP sessions?What are the limitations of using PHP sessions?Apr 30, 2025 am 12:04 AM

PHPsessionshaveseverallimitations:1)Storageconstraintscanleadtoperformanceissues;2)Securityvulnerabilitieslikesessionfixationattacksexist;3)Scalabilityischallengingduetoserver-specificstorage;4)Sessionexpirationmanagementcanbeproblematic;5)Datapersis

Explain how load balancing affects session management and how to address it.Explain how load balancing affects session management and how to address it.Apr 29, 2025 am 12:42 AM

Load balancing affects session management, but can be resolved with session replication, session stickiness, and centralized session storage. 1. Session Replication Copy session data between servers. 2. Session stickiness directs user requests to the same server. 3. Centralized session storage uses independent servers such as Redis to store session data to ensure data sharing.

Explain the concept of session locking.Explain the concept of session locking.Apr 29, 2025 am 12:39 AM

Sessionlockingisatechniqueusedtoensureauser'ssessionremainsexclusivetooneuseratatime.Itiscrucialforpreventingdatacorruptionandsecuritybreachesinmulti-userapplications.Sessionlockingisimplementedusingserver-sidelockingmechanisms,suchasReentrantLockinJ

Are there any alternatives to PHP sessions?Are there any alternatives to PHP sessions?Apr 29, 2025 am 12:36 AM

Alternatives to PHP sessions include Cookies, Token-based Authentication, Database-based Sessions, and Redis/Memcached. 1.Cookies manage sessions by storing data on the client, which is simple but low in security. 2.Token-based Authentication uses tokens to verify users, which is highly secure but requires additional logic. 3.Database-basedSessions stores data in the database, which has good scalability but may affect performance. 4. Redis/Memcached uses distributed cache to improve performance and scalability, but requires additional matching

Define the term 'session hijacking' in the context of PHP.Define the term 'session hijacking' in the context of PHP.Apr 29, 2025 am 12:33 AM

Sessionhijacking refers to an attacker impersonating a user by obtaining the user's sessionID. Prevention methods include: 1) encrypting communication using HTTPS; 2) verifying the source of the sessionID; 3) using a secure sessionID generation algorithm; 4) regularly updating the sessionID.

See all articles

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

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function