PHP分頁函數顯示資料

來源:互聯網
上載者:User
最近模訪叔的網站做一個全部評論的頁面,直接調用wp資料庫一些欄位,這都不難,對我一個剛學PHP的菜鳥來說,最難的是分頁功能,一開始我用了一個最基本的分頁代碼實現,但代碼和體驗都很差,只也實現了上下翻頁,後來找到這個函數,還不錯,分享一下:
建立一個mypage.php檔案,後面載入使用即可。
  1. if(!function_exists("pageDivide")){
  2. #$total 資訊總數
  3. #$shownu 顯示數量,預設20
  4. #$url 本頁連結
  5. function pageDivide($total,$shownu=20,$url=''){
  6. #$page 當前頁碼
  7. #$sqlfirst mysql資料庫起始項
  8. #$pagecon 分頁導航內容
  9. global $page,$sqlfirst,$pagecon,$_SERVER;
  10. $GLOBALS["shownu"]=$shownu;
  11. if(isset($_GET['page'])){
  12. $page=$_GET['page'];
  13. }else $page=1;
  14. #如果$url使用預設,即空值,則賦值為本頁URL
  15. if(!$url){ $url=$_SERVER["REQUEST_URI"];}
  16. #URL分析
  17. $parse_url=parse_url($url);
  18. @$url_query=$parse_url["query"]; //取出在問號?之後內容
  19. if($url_query){
  20. $url_query=preg_replace("/(&?)(page=$page)/","",$url_query);
  21. $url = str_replace($parse_url["query"],$url_query,$url);
  22. if($url_query){
  23. $url .= "&page";
  24. }else $url .= "page";
  25. }else $url .= "?page";
  26. #頁碼計算
  27. $lastpg=ceil($total/$shownu); //最後頁,總頁數
  28. $page=min($lastpg,$page);
  29. $prepg=$page-1; //上一頁
  30. $nextpg=($page==$lastpg ? 0 : $page+1); //下一頁
  31. $sqlfirst=($page-1)*$shownu;
  32. #開始分頁導航內容
  33. $pagecon = "顯示第 ".($total?($sqlfirst+1):0)."-".min($sqlfirst+$shownu,$total)." 條記錄,共 $total 條記錄";
  34. if($lastpg<=1) return false; //如果只有一頁則跳出
  35. if($page!=1) $pagecon .=" 首頁 "; else $pagecon .=" 首頁 ";
  36. if($prepg) $pagecon .=" 前頁 "; else $pagecon .=" 前頁 ";
  37. if($nextpg) $pagecon .=" 後頁 "; else $pagecon .=" 後頁 ";
  38. if($page!=$lastpg) $pagecon.=" 尾頁 "; else $pagecon .=" 尾頁 ";
  39. #下拉捷徑清單,迴圈列出所有頁碼
  40. $pagecon .=" 到第 \n";for($i=1;$i<=$lastpg;$i++){if($i==$page) $pagecon .="$i\n";else $pagecon .="$i\n";}$pagecon .=" 頁,共 $lastpg 頁";
  41. }
  42. }else die('pageDivide()同名函數已經存在!');
  43. ?>
複製代碼
  1. require_once('mypage.php');
  2. $result=mysql_query("select * from table", $myconn);
  3. $total=mysql_num_rows($result); //取得資訊總數
  4. pageDivide($total,10); //調用分頁函數,參數二,是每一頁顯示條數
  5. //資料庫操作,select自己資料庫的資料,這裡只是範例,資料庫連結關閉,這裡也不作講解了。
  6. $result=mysql_query("select * from table limit $sqlfirst,$shownu", $myconn);
  7. while($row=mysql_fetch_array($result)){
  8. //資料操作
  9. }
  10. echo $pagecon; //輸出分頁導航內容
  11. ?>
複製代碼
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.