首頁 後端開發 php教程 PHP分頁程式碼詳解(附實例)

PHP分頁程式碼詳解(附實例)

Jul 25, 2016 am 08:52 AM

  1. // 建立資料庫連線

  2. $link = mysql_connect("localhost", "mysql_user", "mysql_Word ")
  3. or die("Could not connect: " . mysql_error());
  4. // 取得目前頁數
  5. if( isset($_GET['page']) ){
  6. $ page = intval( $_GET['page'] );
  7. }
  8. else{
  9. $page = 1;
  10. }
  11. // 每頁數量
  12. $PageSize = 10;
  13. // 取得總資料量
  14. $sql = "select count(*) as amount from table";
  15. $result = mysql_query($sql);
  16. $row = mysql_fetch_row($result) ;
  17. $amount = $row['amount'];
  18. // 記算總共有多少頁
  19. if( $amount ){
  20. if( $amount if( $amount % $page_size ){ //取總資料量除以每頁數的餘數
  21. $page_count = (int )($amount / $page_size) 1; //如果有餘數,則頁數等於總資料量除以每頁數的結果取整數再加一
  22. }else{
  23. $page_count = $amount / $page_size; //如果沒有餘數,則頁數等於總資料量除以每頁數的結果
  24. }
  25. }
  26. else{
  27. $page_count = 0;
  28. }
  29. // 翻頁連結
  30. $page_string = '';
  31. if( $page == 1 ){
  32. $page_string .= '第一頁|上一頁|';
  33. }
  34. else{
  35. $page_string .= '第一頁|上一頁|';
  36. }
  37. if( ($page == $page_count) || ($page_count == 0) ){
  38. $page_string .= '下一頁|尾頁' ;
  39. }
  40. else{
  41. $page_string .= '下一頁|尾頁';
  42. }
  43. // 取得數據,以二維數組格式傳回結果
  44. if( $amount ){
  45. $sql = " select * from table order by id desc limit ". ($page-1)*$page_size .", $page_size";
  46. $result = mysql_query($sql);
  47. while ( $row = mysql_fetch_row($result) ){

  48. $rowset[] = $row;
  49. }
  50. }else{
  51. $rowset = array();
  52. }
  53. / / 沒有包含顯示結果的程式碼,那不在討論範圍,只要用foreach就可以很簡單的用得到的二維數組來顯示結果
  54. ?>
複製程式碼

4、OO風格程式碼 資料庫連線使用pear db類別進行處理。

  1. // FileName: Pager.class.php

  2. // 分頁類,這類僅用於處理資料結構,不負責處理顯示
  3. Class Pager
  4. {
  5. var $PageSize; //每頁的數量
  6. var $CurrentPageID; //目前的頁數
  7. var $NextPageID; / /下一頁
  8. var $PreviousPageID; //上一頁
  9. var $numPages; //總頁數
  10. var $numItems; //總記錄數
  11. var $isFirstPage; //是否第一頁
  12. var $isLastPage; //是否最後一頁
  13. var $sql; //sql查詢語句
  14. function Pager($option)

  15. {
  16. global $db;
  17. $this->_setOptions($option);
  18. // 總條數
  19. if ( !isset($this->numItems) )
  20. {
  21. $res = $db->query($this->sql);
  22. $this->numItems = $res->numRows();
  23. }
  24. // 總頁數
  25. if ( $this ->numItems > 0 )
  26. {
  27. if ( $this->numItems PageSize ){ $this->numPages = 1; }
  28. if ( $this->numItems % $this ->PageSize )
  29. {
  30. $this->numPages= (int)($this->numItems / $this->PageSize) 1;
  31. }
  32. else
  33. {
  34. $this->numPages = $this->numItems / $this->PageSize;
  35. }
  36. }
  37. else
  38. {
  39. $this->numPages = 0;
  40. }
  41. switch ( $this->CurrentPageID )

  42. {
  43. case $this->numPages == 1:
  44. $this->isFirstPage = true;isLastPage = true;
  45. break;
  46. case 1:
  47. $this->isFirstPage = true;
  48. $this->isLastPage = false;
  49. break;
  50. case
  51. this $ ->numPages:
  52. $this->isFirstPage = false;
  53. $this->isLastPage = true;
  54. break;
  55. default:
  56. $this->isFirstPage = 🎜> default:
  57. $this->isFirstPage = false; $this->isLastPage = false;
  58. }
  59. if ( $this->numPages > 1 )

  60. {
  61. if ( !$this->isLastPage ) { $ this->NextPageID = $this->CurrentPageID 1; }
  62. if ( !$this->isFirstPage ) { $this->PreviousPageID = $this->CurrentPageID - 1; }
  63. }
  64. return true;

  65. }
  66. /***

  67. *
  68. * 返回結果集的資料庫連接
  69. * 在結果集比較大的時候可以直接使用這個方法獲得資料庫連接,然後在類別之外遍歷,這樣開銷較小
  70. *如果結果集不是很大,可以直接使用getPageData的方式取得二維陣列格式的結果
  71. * getPageData方法也是呼叫此方法來取得結果的
  72. *
  73. ***/
  74. function getDataLink()

  75. {
  76. if ( $this->numItems )
  77. {
  78. global $db;
  79. $PageID = $this->CurrentPageID;

  80. $ from = ($PageID - 1)*$this->PageSize;

  81. $count = $this->PageSize;
  82. $link = $db->limitQuery($this->sql, $from, $count ); //使用Pear DB::limitQuery方法保證資料庫相容性
  83. return $link;

  84. }
  85. else
  86. {
  87. return false;
  88. }
  89. }
  90. /***

  91. *
  92. * 以二維數組的格式傳回結果集
  93. *
  94. ***/
  95. function getPageData()

  96. {
  97. if ( $this-> numItems )
  98. {
  99. if ( $res = $this->getDataLink() )
  100. {
  101. if ( $res->numRows() )
  102. {
  103. while ( $row = $res->fetchRow() )
  104. {
  105. $result[] = $row;
  106. }
  107. }
  108. else
  109. {
  110. $result = array();
  111. }
  112. return $result;

  113. }
  114. else
  115. {
  116. return false;
  117. }
  118. }
  119. else }
  120. }
  121. else
  122. {
  123. return false;
  124. }
  125. }
  126. function _setOptions($option)

  127. {
  128. $allow_options = array( 'PageSize' ,
  129. 'CurrentPageID',
  130. 'sql',
  131. 'numItems'
  132. );
  133. foreach ( $option as $key => $value )

  134. foreach ( $option as $key => $value )

  135. {
  136. if ( in_array($key, $allow_options) && ($value != null) )
  137. {
  138. $this->$key = $value;
  139. } }

    return true; }

  140. }
  141. ?>
  142. 呼叫範例:

  143. // FileName: test_pager.php
  144. // 省略了使用pear db類別建立資料庫連接的程式碼
  145. require "Pager.class.php";
  146. if ( isset($_GET['page']) )
  147. {
  148. $page = (int)$_GET['page '];
  149. }
  150. else
  151. {
  152. $page = 1;
  153. }
  154. $sql = "select * from table order by id";
  155. $pager_option = array (
  156. "sql" => $sql,
  157. "PageSize" => 10,
  158. "CurrentPageID" => $page
  159. );
  160. if ( isset($_GET['numItems' ]) )
  161. {
  162. $pager_option['numItems'] = (int)$_GET['numItems'];
  163. }
  164. $pager = @new Pager($pager_option);
  165. $data = $pager->getPageData();
  166. if ( $pager->isFirstPage )
  167. {
  168. $turnover = "首頁|上一頁|";
  169. }
  170. else
  171. {
  172. $turnover = "首頁|上一頁|";
  173. }
  174. if ( $pager->isLastPage )
  175. {
  176. $ turnover .= "下一頁|尾頁";
  177. }
  178. else
  179. {
  180. $turnover .= "下一頁|尾頁";
  181. }
  182. ?>
複製程式碼

說明兩點: 這個類別只是處理數據,並不負責處理顯示,因為我覺得將數據的處理和結果的顯示都放到一個類別裡邊實在是有些勉強。 顯示的時候情況和要求多變,不如自己根據類別給出的結果處理,更好的方法是根據這個Pager類別繼承一個自己的子類別來顯示不同的分頁,例如顯示使用者分頁列表:

  1. Class MemberPager extends Pager

  2. {
  3. function showPager extends Pager
  4. {
  5. function showPager()
  6. global $db;
  7. $data = $this->getPageData();

  8. // 顯示結果的程式碼
  9. // ......
  10. }
  11. }
  12. /// 呼叫
  13. if ( isset($_GET['page']) )
  14. {
  15. $page = (int)$_GET['page'];
  16. }
  17. else
  18. {
  19. $page = 1;
  20. }
  21. $sql = "select * from members order by id";
  22. $pager_option = array(
  23. "sql" => $sql,
  24. "PageSize" => 10,
  25. "CurrentPageID" => $page
  26. );
  27. if ( isset($_GET['numItems']) )
  28. {
  29. $pager_option['numItems'] = (int)$_GET['numItems'];
  30. }
  31. $pager = @new MemberPager($pager_option);
  32. $pager-> showMemberList();
  33. ?>
複製程式碼

說明:不同資料庫的相容性,在不同的資料庫中截獲一段結果的寫法是不一樣的。 mysql: select * from table limit offset, rows pgsql: select * from table limit m offset n ..... 因此,在類別裡邊取得結果時,需要使用pear db類別的limitQuery方法。


本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

對基於PHP的API進行版本控制的最佳實踐是什麼? 對基於PHP的API進行版本控制的最佳實踐是什麼? Jun 14, 2025 am 12:27 AM

基於toversionaphp,useUrl deuseUrl specteringforclarityAndEsofRouting,單獨的codetoavoidConflicts,dremecateOldVersionswithClearCommunication,andConsiderCustomHeadeSerlySerallyWhennEnncelsy.startbyplacingtheversionIntheUrl(E.G.,epi/api/v

如何在PHP中實施身份驗證和授權? 如何在PHP中實施身份驗證和授權? Jun 20, 2025 am 01:03 AM

tosecurelyhandleauthenticationandationallizationInphp,lofterTheSesteps:1.AlwaysHashPasswordSwithPassword_hash()andverifyusingspasspassword_verify(),usepreparedStatatementStopreventsqlineptions,andStoreSeruserDatain usseruserDatain $ _sessiveferterlogin.2.implementrole-2.imaccessccsccccccccccccccccccccccccc.

PHP中的程序和麵向對象的編程範例之間有什麼區別? PHP中的程序和麵向對象的編程範例之間有什麼區別? Jun 14, 2025 am 12:25 AM

procemal and object-tiriendedprogromming(oop)inphpdiffersimplessintustructure,可重複使用性和datahandling.1.procedural-Progrogursmingusesfunctimesfunctionsormanized sequalized sequalized sequiential,poiperforsmallscripts.2.OpporganizesCodeOrganizescodeOdeIntsocloceSandObjects,ModelingReal-Worlden-Worlden

PHP中有哪些弱參考(弱圖),何時有用? PHP中有哪些弱參考(弱圖),何時有用? Jun 14, 2025 am 12:25 AM

PHPdoesnothaveabuilt-inWeakMapbutoffersWeakReferenceforsimilarfunctionality.1.WeakReferenceallowsholdingreferenceswithoutpreventinggarbagecollection.2.Itisusefulforcaching,eventlisteners,andmetadatawithoutaffectingobjectlifecycles.3.YoucansimulateaWe

如何在PHP中安全地處理文件上傳? 如何在PHP中安全地處理文件上傳? Jun 19, 2025 am 01:05 AM

要安全處理PHP中的文件上傳,核心在於驗證文件類型、重命名文件並限制權限。 1.使用finfo_file()檢查真實MIME類型,僅允許特定類型如image/jpeg;2.用uniqid()生成隨機文件名,存儲至非Web根目錄;3.通過php.ini和HTML表單限製文件大小,設置目錄權限為0755;4.使用ClamAV掃描惡意軟件,增強安全性。這些步驟有效防止安全漏洞,確保文件上傳過程安全可靠。

PHP中==(鬆散比較)和===(嚴格的比較)之間有什麼區別? PHP中==(鬆散比較)和===(嚴格的比較)之間有什麼區別? Jun 19, 2025 am 01:07 AM

在PHP中,==與===的主要區別在於類型檢查的嚴格程度。 ==在比較前會進行類型轉換,例如5=="5"返回true,而===要求值和類型都相同才會返回true,例如5==="5"返回false。使用場景上,===更安全應優先使用,==僅在需要類型轉換時使用。

如何與PHP的NOSQL數據庫(例如MongoDB,Redis)進行交互? 如何與PHP的NOSQL數據庫(例如MongoDB,Redis)進行交互? Jun 19, 2025 am 01:07 AM

是的,PHP可以通過特定擴展或庫與MongoDB和Redis等NoSQL數據庫交互。首先,使用MongoDBPHP驅動(通過PECL或Composer安裝)創建客戶端實例並操作數據庫及集合,支持插入、查詢、聚合等操作;其次,使用Predis庫或phpredis擴展連接Redis,執行鍵值設置與獲取,推薦phpredis用於高性能場景,Predis則便於快速部署;兩者均適用於生產環境且文檔完善。

如何在PHP( - , *, /,%)中執行算術操作? 如何在PHP( - , *, /,%)中執行算術操作? Jun 19, 2025 pm 05:13 PM

PHP中使用基本數學運算的方法如下:1.加法用 號,支持整數和浮點數,也可用於變量,字符串數字會自動轉換但不推薦依賴;2.減法用-號,變量同理,類型轉換同樣適用;3.乘法用*號,適用於數字及類似字符串;4.除法用/號,需避免除以零,並註意結果可能是浮點數;5.取模用%號,可用於判斷奇偶數,處理負數時餘數符號與被除數一致。正確使用這些運算符的關鍵在於確保數據類型清晰並處理好邊界情況。

See all articles