PHP中常用的分页类总结

php分页是目前在显示大量结果时所采用的最好的方式,有了下面这些代码的帮助,开发人员可以在多个页面中显示大量的数据,在互联网上,分​页是一般用于搜索结果或是浏览全部信息.

php基本分页,代码如下:

  1. <?php
  2. // database connection info
  3. $conn = mysql_connect('localhost','dbusername','dbpass') or trigger_error("SQL", E_USER_ERROR);
  4. $db = mysql_select_db('dbname',$conn) or trigger_error("SQL", E_USER_ERROR);
  5. // find out how many rows are in the table
  6. $sql = "SELECT COUNT(*) FROM numbers";
  7. $result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
  8. $r = mysql_fetch_row($result);
  9. $numrows = $r[0];
  10. // number of rows to show per page
  11. $rowsperpage = 10;
  12. // find out total pages
  13. $totalpages = ceil($numrows / $rowsperpage);
  14. // get the current page or set a default
  15. if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
  16. // cast var as int
  17. $currentpage = (int) $_GET['currentpage'];
  18. } else {
  19. // default page num
  20. $currentpage = 1;
  21. } // end if
  22. // if current page is greater than total pages...
  23. if ($currentpage > $totalpages) {
  24. // set current page to last page
  25. $currentpage = $totalpages;
  26. } // end if
  27. // if current page is less than first page...
  28. if ($currentpage < 1) {
  29. // set current page to first page
  30. $currentpage = 1;
  31. } // end if
  32. // the offset of the list, based on current page
  33. $offset = ($currentpage - 1) * $rowsperpage;
  34. // get the info from the db
  35. $sql = "SELECT id, number FROM numbers LIMIT $offset, $rowsperpage";
  36. $result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
  37. // while there are rows to be fetched...
  38. while ($list = mysql_fetch_assoc($result)) {
  39. // echo data
  40. echo $list['id'] . " : " . $list['number'] . "<br />";
  41. } // end while
  42. /****** build the pagination links ******/
  43. // range of num links to show
  44. $range = 3;
  45. // if not on page 1, don't show back links
  46. if ($currentpage > 1) {
  47. // show << link to go back to page 1
  48. echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1'><<</a> ";
  49. // get previous page num
  50. $prevpage = $currentpage - 1;
  51. // show < link to go back to 1 page
  52. echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage'><</a> ";
  53. } // end if
  54. // loop to show links to range of pages around current page
  55. for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) {
  56. // if it's a valid page number...
  57. if (($x > 0) && ($x <= $totalpages)) {
  58. // if we're on current page...
  59. if ($x == $currentpage) {
  60. // 'highlight' it but don't make a link
  61. echo " [<b>$x</b>] ";
  62. // if not current page...
  63. } else {
  64. // make it a link
  65. echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x'>$x</a> ";
  66. } // end else
  67. } // end if
  68. } // end for
  69. // if not on last page, show forward and last page links
  70. if ($currentpage != $totalpages) {
  71. // get next page
  72. $nextpage = $currentpage + 1;
  73. // echo forward link for next page
  74. echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage'>></a> ";
  75. // echo forward link for lastpage
  76. echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$totalpages'>>></a> ";
  77. } // end if
  78. /****** end build pagination links ******/
  79. ?>

先看一个常用的php分页类,代码如下:

  1. <?php
  2. /*
  3. Place code to connect to your DB here.
  4. */
  5. include('config.php'); // include your code to connect to DB.
  6. $tbl_name=""; //your table name
  7. // How many adjacent pages should be shown on each side?
  8. $adjacents = 3;
  9. /*
  10. First get total number of rows in data table.
  11. If you have a WHERE clause in your query, make sure you mirror it here.
  12. */
  13. $query = "SELECT COUNT(*) as num FROM $tbl_name";
  14. $total_pages = mysql_fetch_array(mysql_query($query));
  15. $total_pages = $total_pages[num];
  16. /* Setup vars for query. */
  17. $targetpage = "filename.php"; //your file name (the name of this file)
  18. $limit = 2; //how many items to show per page
  19. $page = $_GET['page'];
  20. if($page)
  21. $start = ($page - 1) * $limit; //first item to display on this page
  22. else
  23. $start = 0; //if no page var is given, set start to 0
  24. /* Get data. */
  25. $sql = "SELECT column_name FROM $tbl_name LIMIT $start, $limit";
  26. $result = mysql_query($sql);
  27. /* Setup page vars for display. */
  28. if ($page == 0) $page = 1; //if no page var is given, default to 1.
  29. $prev = $page - 1; //previous page is page - 1
  30. $next = $page + 1; //next page is page + 1
  31. $lastpage = ceil($total_pages/$limit); //lastpage is = total pages / items per page, rounded up.
  32. $lpm1 = $lastpage - 1; //last page minus 1
  33. /*
  34. Now we apply our rules and draw the pagination object.
  35. We're actually saving the code to a variable in case we want to draw it more than once.
  36. */
  37. $pagination = "";
  38. if($lastpage > 1)
  39. {
  40. $pagination .= "<div class="pagination">";
  41. //previous button
  42. if ($page > 1)
  43. $pagination.= "<a href="$targetpage?page=$prev">� previous</a>";
  44. else
  45. $pagination.= "<span class="disabled">� previous</span>";
  46. //pages
  47. if ($lastpage < 7 + ($adjacents * 2)) //not enough pages to bother breaking it up
  48. {
  49. for ($counter = 1; $counter <= $lastpage; $counter++)
  50. {
  51. if ($counter == $page)
  52. $pagination.= "<span class="current">$counter</span>";
  53. else
  54. $pagination.= "<a href="$targetpage?page=$counter">$counter</a>";
  55. }
  56. }
  57. elseif($lastpage > 5 + ($adjacents * 2)) //enough pages to hide some
  58. {
  59. //close to beginning; only hide later pages
  60. if($page < 1 + ($adjacents * 2))
  61. {
  62. for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++)
  63. {
  64. if ($counter == $page)
  65. $pagination.= "<span class="current">$counter</span>";
  66. else
  67. $pagination.= "<a href="$targetpage?page=$counter">$counter</a>";
  68. }
  69. $pagination.= "...";
  70. $pagination.= "<a href="$targetpage?page=$lpm1">$lpm1</a>";
  71. $pagination.= "<a href="$targetpage?page=$lastpage">$lastpage</a>";
  72. }
  73. //in middle; hide some front and some back
  74. elseif($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2))
  75. {
  76. $pagination.= "<a href="$targetpage?page=1">1</a>";
  77. $pagination.= "<a href="$targetpage?page=2">2</a>";
  78. $pagination.= "...";
  79. for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++)
  80. {
  81. if ($counter == $page)
  82. $pagination.= "<span class="current">$counter</span>";
  83. else
  84. $pagination.= "<a href="$targetpage?page=$counter">$counter</a>";
  85. }
  86. $pagination.= "...";
  87. $pagination.= "<a href="$targetpage?page=$lpm1">$lpm1</a>";
  88. $pagination.= "<a href="$targetpage?page=$lastpage">$lastpage</a>";
  89. }
  90. //close to end; only hide early pages
  91. else
  92. {
  93. $pagination.= "<a href="$targetpage?page=1">1</a>";
  94. $pagination.= "<a href="$targetpage?page=2">2</a>";
  95. $pagination.= "...";
  96. for ($counter = $lastpage - (2 + ($adjacents * 2)); $counter <= $lastpage; $counter++)
  97. {
  98. if ($counter == $page)
  99. $pagination.= "<span class="current">$counter</span>";
  100. else
  101. $pagination.= "<a href="$targetpage?page=$counter">$counter</a>";
  102. }
  103. }
  104. }
  105. //next button
  106. if ($page < $counter - 1)
  107. $pagination.= "<a href="$targetpage?page=$next">next �</a>";
  108. else
  109. $pagination.= "<span class="disabled">next �</span>";
  110. $pagination.= "</div>n";
  111. }//开源代码phpfensi.com
  112. ?>
  113. <?php
  114. while($row = mysql_fetch_array($result))
  115. {
  116. // Your while loop here
  117. }
  118. ?>
  119. <?=$pagination?>

实例代码如下:

  1. <?php
  2. class PageView{
  3. /**页码**/
  4. public $pageNo = 1;
  5. /**页大小**/
  6. public $pageSize = 20;
  7. /**共多少页**/
  8. public $pageCount = 0;
  9. /**总记录数**/
  10. public $totalNum = 0;
  11. /**偏移量,当前页起始行**/
  12. public $offSet = 0;
  13. /**每页数据**/
  14. public $pageData = array();
  15. /**是否有上一页**/
  16. public $hasPrePage = true;
  17. /**是否有下一页**/
  18. public $hasNextPage = true;
  19. public $pageNoList = array();
  20. public $jsFunction ='jsFunction';
  21. /**
  22. *
  23. * @param unknown_type $count 总行数
  24. * @param unknown_type $size 分页大小
  25. * @param unknown_type $string
  26. */
  27. public function __construct($count=0, $size=20,$pageNo=1,$pageData =array(),$jsFunction='jsFunction'){
  28. $this->totalNum = $count;//总记录数
  29. $this->pageSize = $size;//每页大小
  30. $this->pageNo = $pageNo;
  31. //计算总页数
  32. $this->pageCount = ceil($this->totalNum/$this->pageSize);
  33. $this->pageCount = ($this->pageCount<=0)?1:$this->pageCount;
  34. //检查pageNo
  35. $this->pageNo = $this->pageNo == 0 ? 1 : $this->pageNo;
  36. $this->pageNo = $this->pageNo > $this->pageCount? $this->pageCount : $this->pageNo;
  37. //计算偏移
  38. $this->offset = ( $this->pageNo - 1 ) * $this->pageSize;
  39. //计算是否有上一页下一页
  40. $this->hasPrePage = $this->pageNo == 1 ?false:true;
  41. $this->hasNextPage = $this->pageNo >= $this->pageCount ?false:true;
  42. $this->pageData = $pageData;
  43. $this->jsFunction = $jsFunction;
  44. }
  45. /**
  46. * 分页算法
  47. * @return
  48. */
  49. private function generatePageList(){
  50. $pageList = array();
  51. if($this->pageCount <= 9){
  52. for($i=0;$i<$this->pageCount;$i++){
  53. array_push($pageList,$i+1);
  54. }
  55. }else{
  56. if($this->pageNo <= 4){
  57. for($i=0;$i<5;$i++){
  58. array_push($pageList,$i+1);
  59. }
  60. array_push($pageList,-1);
  61. array_push($pageList,$this->pageCount);
  62. }else if($this->pageNo > $this->pageCount - 4){
  63. array_push($pageList,1);
  64. array_push($pageList,-1);
  65. for($i=5;$i>0;$i--){
  66. array_push($pageList,$this->pageCount - $i+1);
  67. }
  68. }else if($this->pageNo > 4 && $this->pageNo <= $this->pageCount - 4){
  69. array_push($pageList,1);
  70. array_push($pageList,-1);
  71. array_push($pageList,$this->pageNo -2);
  72. array_push($pageList,$this->pageNo -1);
  73. array_push($pageList,$this->pageNo);
  74. array_push($pageList,$this->pageNo + 1);
  75. array_push($pageList,$this->pageNo + 2);
  76. array_push($pageList,-1);
  77. array_push($pageList,$this->pageCount);
  78. }
  79. }
  80. return $pageList;
  81. }
  82. /***
  83. * 创建分页控件
  84. * @param
  85. * @return String
  86. */
  87. public function echoPageAsDiv(){
  88. $pageList = $this->generatePageList();
  89. $pageString ="<div class='pagination'><div class='page-bottom'>";
  90. if(!emptyempty($pageList)){
  91. if($this->pageCount >1){
  92. if($this->hasPrePage){
  93. $pageString = $pageString ."<a class='page-next' href="javascript:" .$this->jsFunction . "(" . ($this->pageNo-1) . ")">上一页</a>";
  94. }
  95. foreach ($pageList as $k=>$p){
  96. if($this->pageNo == $p){
  97. $pageString = $pageString ."<span class='page-cur'>" . $this->pageNo . "</span>";
  98. continue;
  99. }
  100. if($p == -1){
  101. $pageString = $pageString ."<span class='page-break'>...</span>";
  102. continue;
  103. }
  104. $pageString = $pageString ."<a href="javascript:" .$this->jsFunction . "(" . $p . ")">" . $p . "</a>";
  105. }
  106. if($this->hasNextPage){
  107. $pageString = $pageString ."<a class='page-next' href="javascript:" .$this->jsFunction . "(" . ($this->pageNo+1) . ")">下一页</a>";
  108. }
  109. }
  110. }
  111. $pageString = $pageString .("</div></div>");
  112. return $pageString;
  113. }
  114. }
  115. ?>

css代码如下:

  1. <style type="text/css">
  2. <!--
  3. .pagination {font-family: Tahoma;overflow: hidden; padding-top: 12px; text-align: center;}
  4. .pagination-tab { margin-bottom: 20px;}
  5. .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 {
  6. 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;}
  7. .pagination a, .pagination .page-prev_g, .pagination .page-prev, .pagination .page-next, .pagination .page-next_g, .pagination .page-cur, .pagination .page-break {
  8. border: 1px solid #ed3d83; color:#e9357d; font-weight:bold;}
  9. .pagination a:hover { border: 1px solid #ed3d83;text-decoration: none; background-color:#f95f9d; color:#fff;}
  10. .pagination .page-prev_g, .pagination .page-prev, .pagination .page-next, .pagination .page-next_g { width: 36px; background-image: url(../static/img/page.gif);}
  11. .pagination .page-prev { background-position: -0px -38px; padding-left: 16px;}
  12. .pagination .page-prev_g { background-position:0px -59px; padding-left: 16px; color:#cbcbcb; font-weight:normal;}
  13. .pagination .page-next { background-position: 0px 0px; padding-right: 16px; font-weight:normal;}
  14. .pagination .page-next_g { background-position: -0px -19px; padding-right: 16px; color:#cbcbcb;}
  15. .pagination .page-cur {background-color: #f95f9d; border: 1px solid #ed3d83;color: #fff;font-weight: bold;}
  16. .pagination .page-break {border: medium none; background:none transparent; color:#333;}
  17. -->
  18. </style>

在php页面中的调用方法,代码如下:

  1. $pageNo = $_GET['pageNo'];
  2. if(emptyempty($pageNo)){
  3. $pageNo = 1;
  4. }
  5. //分页数据
  6. $pageData = News::getNewsPage($pageNo,$pageSize);
  7. //取得总行数
  8. $count = News::getNewsCount();
  9. //创建分页器
  10. $p = new PageView($count['0']['TOTAL'],$pageSize,$pageNo,$pageData);
  11.      //生成页码
  12. $pageViewString = $p->echoPageAsDiv();