Home >Backend Development >PHP Tutorial >Newbie try-php paging example code

Newbie try-php paging example code

WBOY
WBOYOriginal
2016-07-25 09:05:21830browse
  1. /*
  2. test数据库,一个test表,唯一字段Id,作为测试使用
  3. @link http://bbs.it-home.org
  4. */
  5. $conn = mysql_connect("localhost","root","");
  6. $maxnum = 2; //每页显示记录条数
  7. mysql_select_db("test", $conn);
  8. $query1 = "SELECT COUNT(*) AS totalrows FROM test ";
  9. $result1 = mysql_query($query1, $conn) or die(mysql_error());
  10. $row1 = mysql_fetch_assoc($result1);
  11. $totalRows1 = $row1['totalrows']; //数据集数据总条数
  12. $totalpages = ceil($totalRows1/$maxnum);//计算可分页总数,ceil()为上舍函数
  13. if(!isset($_GET['page']) || !intval($_GET['page']) || $_GET['page'] > $totalpages) $page = 1; //对3种出错进行默认处理
  14. //在url参数page不存在时,page不为10进制数时,page大于可分页数时,默认为1
  15. else $page = $_GET['page'];
  16. $startnum = ($page - 1)*$maxnum; //从数据集第$startnum条开始取,注意数据集是从0开始的
  17. $query = "SELECT * FROM test LIMIT $startnum,$maxnum";//选择出符合要求的数据 从$startnum条数据开始,选出$maxnum行
  18. $result = mysql_query($query, $conn) or die(mysql_error());
  19. $row = mysql_fetch_assoc($result);
  20. ?>
  21. 分页示例
  22. do {
  23. ?>
  24. 分页示例
  25. < ;/table>
  26. echo "Total$totalRows1records";
  27. echo ""."/".$totalpages."page";
  28. //Implementation<< < 1 2 3 4 5> >> Pagination link
  29. $pre = $page - 1;//Previous page
  30. $next = $page + 1;//Next page
  31. $maxpages = 4;//When processing paging<< < 1 2 3 4 > > >Display 4 pages
  32. $pagepre = 1;//If the current page is 4, the previous $pagepre page should also be displayed, such as << < 3 /4/ 5 6 > >> Display it
  33. if($page != 1) { echo "<< ";
  34. echo "< a href='".$_SERVER['PHP_SELF'].'?page='.$pre."'>< ";}
  35. if($maxpages>=$totalpages) //if The total records are not enough to display 4 pages
  36. {$pgstart = 1;$pgend = $totalpages;}//There is no page printing process
  37. elseif(($page-$pagepre-1+$maxpages)>$totalpages) //Just like the total number of pages is 6 and the current number is 5, the previous 3 4 should be displayed, not just 4
  38. {$pgstart = $totalpages - $maxpages + 1;$pgend = $totalpages;}
  39. else{
  40. $pgstart=(($page<=$pagepre)?1:($page-$pagepre));//When the current page is 1, it will only be 1 2 3 4 > >> instead of will be 0 1 2 3 > >>
  41. $pgend=(($pgstart==1)?$maxpages:($pgstart+$maxpages-1));
  42. }
  43. for($pg=$pgstart;$ pg<=$pgend;$pg++){ //Jump menu
  44. if($pg == $page) echo "$pg ";
  45. else echo "$pg ";
  46. }
  47. if($page != $totalpages)
  48. {echo "> ";
  49. echo "> ;> ";}
  50. ?>
  51. No records
  52. mysql_free_result($result1);
  53. mysql_free_result($result);
  54. ?>
Copy code


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