雅安论坛

标题: PHP简单分页省略中间页码 [打印本页]

作者: 匿名    时间: 2021-7-20 22:36
标题: PHP简单分页省略中间页码
  1. <?php
  2. /**
  3.   * @desc created by sublime text3
  4.   * @author jxl <[57953279@qq.com>]>
  5.   * @since 2017/05/06 23:06
  6.   */
  7. $host="localhost";
  8. $user='root';
  9. $pass='';
  10. $link=mysql_connect($host,$user,$pass) or die('数据库连接失败');
  11. mysql_select_db('demo');
  12. mysql_query('set names "utf8"');

  13. $pageSize=10;//每页5条
  14. $bothNum=4;//当前页左右各显示4个页码
  15. $cur_page=isset($_GET['cur_page'])?$_GET['cur_page']:1;//当前页数

  16. $sql="select * from test_db";
  17. $res=mysql_query($sql);
  18. $total=mysql_num_rows($res);//总记录数
  19. $pageNum=ceil($total/$pageSize);//总页数

  20. $start=($cur_page-1)*$pageSize;
  21. $sql="select * from test_db limit $start,$pageSize";
  22. $res=mysql_query($sql);
  23. while ($row=mysql_fetch_array($res)) {
  24.      echo $row['id'].'---'.$row['name'].'---'.$row['age'];
  25.      echo '<hr/>';
  26. }

  27. //上一页
  28. $pagestr="";
  29. if($cur_page==1){
  30.      $pagestr.='<span>上一页</span>';
  31. }else{
  32.      $lastPage=$cur_page-1;
  33.      $pagestr.="<a href='mysqldemo.php?cur_page=$lastPage'>上一页</a>"."  ";
  34. }
  35. // 想象分页如下,目前第 10 页,它两边最多只有 4 (bothnum) 个数字
  36. // 1 ...  6 7 8 9 *10* 11 12 13 14 15 ... 100
  37. // echo $pagestr;
  38. // 首页
  39. if($cur_page-$bothNum>1){
  40.      $pagestr.="<a href='mysqldemo.php?cur_page=1'>首页</a>";
  41.      $pagestr.="<span>...</span>";
  42. }
  43. //当前页的左边
  44. for($i=$bothNum;$i>=1;$i--){
  45.      if(($cur_page - $i) < 1 ) { // 当前页左边花最多 bothnum 个数字
  46.           continue;
  47.       }
  48.      $lastPage=$cur_page-$i;
  49.      $pagestr.="<a href='mysqldemo.php?cur_page=$lastPage'>$lastPage</a>"."  ";
  50. }
  51. //当前页
  52. $pagestr.="<span>$cur_page</span>"."  ";
  53. //当前页右边
  54. for($i=1;$i<=$bothNum;$i++){
  55.      if(($cur_page + $i) > $pageNum) { // 当前页右边最多 bothnum 个数字
  56.          break;
  57.      }
  58.      $lastPage=$cur_page+$i;
  59.      $pagestr.="<a href='mysqldemo.php?cur_page=$lastPage'>$lastPage</a>"."  ";

  60. }

  61. //尾页
  62. if(($cur_page+$bothNum)<$pageNum){
  63.      $pagestr.="<span>...</span>"."  ";
  64.      $pagestr .= '<a href="?cur_page='.$pageNum.'">尾页</a>'."  ";
  65. }
  66. //下一页
  67.   if($cur_page == $pageNum) {
  68.         $pagestr .= '<span>下一页</span>';
  69.     } else {
  70.            $nextPage=$cur_page+1;
  71.         $pagestr .= "<a href='mysqldemo.php?cur_page={$nextPage}'>下一页</a>";
  72.     }
  73. echo $pagestr;
  74. echo "<hr/>";
  75. echo '当前页数为:'.$cur_page.',总页数为:'.$pageNum;
复制代码







欢迎光临 雅安论坛 (https://www.yaanbbs.net/) Powered by Discuz! X3.4