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

  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
PHP中的依賴注入:避免常見的陷阱PHP中的依賴注入:避免常見的陷阱May 16, 2025 am 12:17 AM

DependencyInjection(DI)inPHPenhancescodeflexibilityandtestabilitybydecouplingdependencycreationfromusage.ToimplementDIeffectively:1)UseDIcontainersjudiciouslytoavoidover-engineering.2)Avoidconstructoroverloadbylimitingdependenciestothreeorfour.3)Adhe

如何加快PHP網站:性能調整如何加快PHP網站:性能調整May 16, 2025 am 12:12 AM

到Improveyourphpwebsite的實力,UsEthestertate:1)emplastOpCodeCachingWithOpcachetCachetOspeedUpScriptInterpretation.2)優化的atabasequesquesquesquelies berselectingOnlynlynnellynnessaryfields.3)usecachingsystemssslikeremememememcachedisemcachedtoredtoredtoredsatabaseloadch.4)

通過PHP發送大規模電子郵件:有可能嗎?通過PHP發送大規模電子郵件:有可能嗎?May 16, 2025 am 12:10 AM

是的,ItispossibletosendMassemailswithp.1)uselibrarieslikeLikePhpMailerorSwiftMailerForeffitedEmailsending.2)enasledeLaysBetenemailstoavoidSpamflagssspamflags.3))

PHP中依賴注入的目的是什麼?PHP中依賴注入的目的是什麼?May 16, 2025 am 12:10 AM

DependencyInjection(DI)inPHPisadesignpatternthatachievesInversionofControl(IoC)byallowingdependenciestobeinjectedintoclasses,enhancingmodularity,testability,andflexibility.DIdecouplesclassesfromspecificimplementations,makingcodemoremanageableandadapt

如何使用PHP發送電子郵件?如何使用PHP發送電子郵件?May 16, 2025 am 12:03 AM

使用PHP發送電子郵件的最佳方法包括:1.使用PHP的mail()函數進行基本發送;2.使用PHPMailer庫發送更複雜的HTML郵件;3.使用SendGrid等事務性郵件服務提高可靠性和分析能力。通過這些方法,可以確保郵件不僅到達收件箱,還能吸引收件人。

如何計算PHP多維數組的元素總數?如何計算PHP多維數組的元素總數?May 15, 2025 pm 09:00 PM

計算PHP多維數組的元素總數可以使用遞歸或迭代方法。 1.遞歸方法通過遍歷數組並遞歸處理嵌套數組來計數。 2.迭代方法使用棧來模擬遞歸,避免深度問題。 3.array_walk_recursive函數也能實現,但需手動計數。

PHP中do-while循環有什麼特點?PHP中do-while循環有什麼特點?May 15, 2025 pm 08:57 PM

在PHP中,do-while循環的特點是保證循環體至少執行一次,然後再根據條件決定是否繼續循環。 1)它在條件檢查之前執行循環體,適合需要確保操作至少執行一次的場景,如用戶輸入驗證和菜單系統。 2)然而,do-while循環的語法可能導致新手困惑,且可能增加不必要的性能開銷。

PHP中如何哈希字符串?PHP中如何哈希字符串?May 15, 2025 pm 08:54 PM

在PHP中高效地哈希字符串可以使用以下方法:1.使用md5函數進行快速哈希,但不適合密碼存儲。 2.使用sha256函數提高安全性。 3.使用password_hash函數處理密碼,提供最高安全性和便捷性。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

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

熱門文章

北端:融合系統,解釋
1 個月前By尊渡假赌尊渡假赌尊渡假赌
Mandragora:巫婆樹的耳語 - 如何解鎖抓鉤
4 週前By尊渡假赌尊渡假赌尊渡假赌
<🎜>掩蓋:探險33-如何獲得完美的色度催化劑
2 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。