程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> 關於PHP編程 >> PHP中常用的分頁類總結

PHP中常用的分頁類總結

編輯:關於PHP編程

分頁是目前在顯示大量結果時所采用的最好的方式。有了下面這些代碼的幫助,開發人員可以在多個頁面中顯示大量的數據。在互聯網上,分​頁是一般用於搜索結果或是浏覽全部信息

php基本分頁

 代碼如下 復制代碼

<?php
// database connection info
$conn = mysql_connect('localhost','dbusername','dbpass') or trigger_error("SQL", E_USER_ERROR);
$db = mysql_select_db('dbname',$conn) or trigger_error("SQL", E_USER_ERROR);

// find out how many rows are in the table
$sql = "SELECT COUNT(*) FROM numbers";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
$r = mysql_fetch_row($result);
$numrows = $r[0];

// number of rows to show per page
$rowsperpage = 10;
// find out total pages
$totalpages = ceil($numrows / $rowsperpage);

// get the current page or set a default
if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
// cast var as int
$currentpage = (int) $_GET['currentpage'];
} else {
// default page num
$currentpage = 1;
} // end if

// if current page is greater than total pages...
if ($currentpage > $totalpages) {
// set current page to last page
$currentpage = $totalpages;
} // end if
// if current page is less than first page...
if ($currentpage < 1) {
// set current page to first page
$currentpage = 1;
} // end if

// the offset of the list, based on current page
$offset = ($currentpage - 1) * $rowsperpage;

// get the info from the db
$sql = "SELECT id, number FROM numbers LIMIT $offset, $rowsperpage";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);

// while there are rows to be fetched...
while ($list = mysql_fetch_assoc($result)) {
// echo data
echo $list['id'] . " : " . $list['number'] . "<br />";
} // end while

/****** build the pagination links ******/
// range of num links to show
$range = 3;

// if not on page 1, don't show back links
if ($currentpage > 1) {
// show << link to go back to page 1
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1'><<</a> ";
// get previous page num
$prevpage = $currentpage - 1;
// show < link to go back to 1 page
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage'><</a> ";
} // end if

// loop to show links to range of pages around current page
for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) {
// if it's a valid page number...
if (($x > 0) && ($x <= $totalpages)) {
// if we're on current page...
if ($x == $currentpage) {
// 'highlight' it but don't make a link
echo " [<b>$x</b>] ";
// if not current page...
} else {
// make it a link
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x'>$x</a> ";
} // end else
} // end if
} // end for

// if not on last page, show forward and last page links
if ($currentpage != $totalpages) {
// get next page
$nextpage = $currentpage + 1;
// echo forward link for next page
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage'>></a> ";
// echo forward link for lastpage
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$totalpages'>>></a> ";
} // end if
/****** end build pagination links ******/
?>

先看一個常用的php分頁類

 代碼如下 復制代碼

<?php
 /*
  Place code to connect to your DB here.
 */
 include('config.php'); // include your code to connect to DB.

 $tbl_name="";  //your table name
 // How many adjacent pages should be shown on each side?
 $adjacents = 3;
 
 /*
    First get total number of rows in data table.
    If you have a WHERE clause in your query, make sure you mirror it here.
 */
 $query = "SELECT COUNT(*) as num FROM $tbl_name";
 $total_pages = mysql_fetch_array(mysql_query($query));
 $total_pages = $total_pages[num];
 
 /* Setup vars for query. */
 $targetpage = "filename.php";  //your file name  (the name of this file)
 $limit = 2;         //how many items to show per page
 $page = $_GET['page'];
 if($page)
  $start = ($page - 1) * $limit;    //first item to display on this page
 else
  $start = 0;        //if no page var is given, set start to 0
 
 /* Get data. */
 $sql = "SELECT column_name FROM $tbl_name LIMIT $start, $limit";
 $result = mysql_query($sql);
 
 /* Setup page vars for display. */
 if ($page == 0) $page = 1;     //if no page var is given, default to 1.
 $prev = $page - 1;       //previous page is page - 1
 $next = $page + 1;       //next page is page + 1
 $lastpage = ceil($total_pages/$limit);  //lastpage is = total pages / items per page, rounded up.
 $lpm1 = $lastpage - 1;      //last page minus 1
 
 /*
  Now we apply our rules and draw the pagination object.
  We're actually saving the code to a variable in case we want to draw it more than once.
 */
 $pagination = "";
 if($lastpage > 1)
 { 
  $pagination .= "<div class="pagination">";
  //previous button
  if ($page > 1)
   $pagination.= "<a href="$targetpage?page=$prev">� previous</a>";
  else
   $pagination.= "<span class="disabled">� previous</span>"; 
  
  //pages 
  if ($lastpage < 7 + ($adjacents * 2)) //not enough pages to bother breaking it up
  { 
   for ($counter = 1; $counter <= $lastpage; $counter++)
   {
    if ($counter == $page)
     $pagination.= "<span class="current">$counter</span>";
    else
     $pagination.= "<a href="$targetpage?page=$counter">$counter</a>";     
   }
  }
  elseif($lastpage > 5 + ($adjacents * 2)) //enough pages to hide some
  {
   //close to beginning; only hide later pages
   if($page < 1 + ($adjacents * 2))  
   {
    for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++)
    {
     if ($counter == $page)
      $pagination.= "<span class="current">$counter</span>";
     else
      $pagination.= "<a href="$targetpage?page=$counter">$counter</a>";     
    }
    $pagination.= "...";
    $pagination.= "<a href="$targetpage?page=$lpm1">$lpm1</a>";
    $pagination.= "<a href="$targetpage?page=$lastpage">$lastpage</a>";  
   }
   //in middle; hide some front and some back
   elseif($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2))
   {
    $pagination.= "<a href="$targetpage?page=1">1</a>";
    $pagination.= "<a href="$targetpage?page=2">2</a>";
    $pagination.= "...";
    for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++)
    {
     if ($counter == $page)
      $pagination.= "<span class="current">$counter</span>";
     else
      $pagination.= "<a href="$targetpage?page=$counter">$counter</a>";     
    }
    $pagination.= "...";
    $pagination.= "<a href="$targetpage?page=$lpm1">$lpm1</a>";
    $pagination.= "<a href="$targetpage?page=$lastpage">$lastpage</a>";  
   }
   //close to end; only hide early pages
   else
   {
    $pagination.= "<a href="$targetpage?page=1">1</a>";
    $pagination.= "<a href="$targetpage?page=2">2</a>";
    $pagination.= "...";
    for ($counter = $lastpage - (2 + ($adjacents * 2)); $counter <= $lastpage; $counter++)
    {
     if ($counter == $page)
      $pagination.= "<span class="current">$counter</span>";
     else
      $pagination.= "<a href="$targetpage?page=$counter">$counter</a>";     
    }
   }
  }
  
  //next button
  if ($page < $counter - 1)
   $pagination.= "<a href="$targetpage?page=$next">next �</a>";
  else
   $pagination.= "<span class="disabled">next �</span>";
  $pagination.= "</div>n";  
 }
?>

 <?php
  while($row = mysql_fetch_array($result))
  {
 
  // Your while loop here
 
  }
 ?>

<?=$pagination?>
 


實例

 代碼如下 復制代碼

<?php
class PageView{
    /**頁碼**/
    public $pageNo = 1;
    /**頁大小**/
    public $pageSize = 20;
    /**共多少頁**/
    public $pageCount = 0;
    /**總記錄數**/
    public $totalNum = 0;
    /**偏移量,當前頁起始行**/
    public $offSet = 0;
    /**每頁數據**/
    public $pageData = array();
   
    /**是否有上一頁**/
    public $hasPrePage = true;
    /**是否有下一頁**/
    public $hasNextPage = true;
   
    public $pageNoList = array();
   
    public $jsFunction ='jsFunction';
    /**
     *
     * @param unknown_type $count 總行數
     * @param unknown_type $size 分頁大小
     * @param unknown_type $string
     */
    public function __construct($count=0, $size=20,$pageNo=1,$pageData =array(),$jsFunction='jsFunction'){

        $this->totalNum = $count;//總記錄數
        $this->pageSize = $size;//每頁大小
        $this->pageNo = $pageNo;
        //計算總頁數
        $this->pageCount = ceil($this->totalNum/$this->pageSize);
        $this->pageCount = ($this->pageCount<=0)?1:$this->pageCount;
        //檢查pageNo
        $this->pageNo = $this->pageNo == 0 ? 1 : $this->pageNo;
        $this->pageNo = $this->pageNo > $this->pageCount? $this->pageCount : $this->pageNo;
       
        //計算偏移
        $this->offset = ( $this->pageNo - 1 ) * $this->pageSize;
        //計算是否有上一頁下一頁
        $this->hasPrePage = $this->pageNo == 1 ?false:true;

        $this->hasNextPage = $this->pageNo >= $this->pageCount ?false:true;
       
        $this->pageData = $pageData;
        $this->jsFunction = $jsFunction;
       
    }
    /**
     * 分頁算法
     * @return
     */
    private function generatePageList(){
        $pageList = array();
        if($this->pageCount <= 9){
            for($i=0;$i<$this->pageCount;$i++){
                array_push($pageList,$i+1);
            }
        }else{
            if($this->pageNo <= 4){
                for($i=0;$i<5;$i++){
                    array_push($pageList,$i+1);
                }
                array_push($pageList,-1);
                array_push($pageList,$this->pageCount);

            }else if($this->pageNo > $this->pageCount - 4){
                array_push($pageList,1);
               
                array_push($pageList,-1);
                for($i=5;$i>0;$i--){
                    array_push($pageList,$this->pageCount - $i+1);
                }
            }else if($this->pageNo > 4 && $this->pageNo <= $this->pageCount - 4){
                array_push($pageList,1);
                array_push($pageList,-1);
               
                array_push($pageList,$this->pageNo -2);
                array_push($pageList,$this->pageNo -1);
                array_push($pageList,$this->pageNo);
                array_push($pageList,$this->pageNo + 1);
                array_push($pageList,$this->pageNo + 2);
               
                array_push($pageList,-1);
                array_push($pageList,$this->pageCount);
               
            }
        }
        return $pageList;
    }

    /***
     * 創建分頁控件
    * @param
    * @return String
    */
    public function echoPageAsDiv(){
        $pageList = $this->generatePageList();
       
        $pageString ="<div class='pagination'><div class='page-bottom'>";
   
        if(!empty($pageList)){
            if($this->pageCount >1){
                if($this->hasPrePage){
                    $pageString = $pageString ."<a class='page-next' href="javascript:" .$this->jsFunction . "(" . ($this->pageNo-1) . ")">上一頁</a>";
                }
                foreach ($pageList as $k=>$p){
                    if($this->pageNo == $p){
                        $pageString = $pageString ."<span class='page-cur'>" . $this->pageNo . "</span>";
                        continue;
                    }
                    if($p == -1){
                        $pageString = $pageString ."<span class='page-break'>...</span>";
                        continue;
                    }
                    $pageString = $pageString ."<a href="javascript:" .$this->jsFunction . "(" . $p . ")">" . $p . "</a>";
                }
               
                if($this->hasNextPage){
                    $pageString = $pageString ."<a class='page-next' href="javascript:" .$this->jsFunction . "(" . ($this->pageNo+1) . ")">下一頁</a>";
                }
               
            }
        }
        $pageString = $pageString .("</div></div>");
        return $pageString;
    }
}

?>

css代碼

 代碼如下 復制代碼

<style type="text/css">
<!--
.pagination {font-family: Tahoma;overflow: hidden; padding-top: 12px; text-align: center;}
.pagination-tab { margin-bottom: 20px;}
.pagination a, .pagination .page-cur, .pagination .page-prev_g, .pagination .page-prev, .pagination .page-next, .pagination .page-next_g, .pagination .page-break, .pagination .page-skip {
    display: inline-block;font-family: Tahoma,SimSun,Arial; height: 22px;line-height:22px; margin: 0; min-width: 16px;padding: 0 5px; text-align: center; vertical-align: top; white-space: nowrap;}
.pagination a, .pagination .page-prev_g, .pagination .page-prev, .pagination .page-next, .pagination .page-next_g, .pagination .page-cur, .pagination .page-break {
    border: 1px solid #ed3d83; color:#e9357d; font-weight:bold;}
.pagination a:hover { border: 1px solid #ed3d83;text-decoration: none; background-color:#f95f9d; color:#fff;}
.pagination .page-prev_g, .pagination .page-prev, .pagination .page-next, .pagination .page-next_g { width: 36px; background-image: url(../static/img/page.gif);}
.pagination .page-prev { background-position: -0px -38px; padding-left: 16px;}
.pagination .page-prev_g { background-position:0px -59px; padding-left: 16px; color:#cbcbcb; font-weight:normal;}
.pagination .page-next { background-position: 0px 0px; padding-right: 16px; font-weight:normal;}
.pagination .page-next_g { background-position: -0px -19px; padding-right: 16px; color:#cbcbcb;}
.pagination .page-cur {background-color: #f95f9d; border: 1px solid #ed3d83;color: #fff;font-weight: bold;}
.pagination .page-break {border: medium none; background:none transparent; color:#333;}

-->
</style>

在php頁面中的調用方法

 代碼如下 復制代碼

    $pageNo = $_GET['pageNo'];
        if(empty($pageNo)){
            $pageNo = 1;
        }
        //分頁數據
        $pageData = News::getNewsPage($pageNo,$pageSize);
       //取得總行數
        $count = News::getNewsCount();
        //創建分頁器
        $p = new PageView($count['0']['TOTAL'],$pageSize,$pageNo,$pageData);
     //生成頁碼
        $pageViewString = $p->echoPageAsDiv();


  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved