当前位置:Gxlcms > PHP教程 > 你不可错过的一个php分页类(mysql)

你不可错过的一个php分页类(mysql)

时间:2021-07-01 10:21:17 帮助过:20人阅读

  1. /*

  2. mysql_pager.class.php
  3. 三个参数:mysql_query()的结果, url变量page, 您要的每页记录数
  4. */

  5. class mysql_pager {

  6. // define properties
  7. var $page;
  8. var $result;
  9. var $results_per_page = 3;
  10. var $total_pages;

  11. /*

  12. Define the methods

  13. 下面是构造函数,和类同名(>php4),需要查询的结果句柄,当前页码,每页记录数

  14. like: $f->mysql_pager($result, 1, 15);
  15. */
  16. function mysql_pager( $result, $current_page, $results_per_page ) {
  17. if(!$result){
  18. echo "数据库未运行,结果集错误\n";
  19. return;
  20. }

  21. $this->result = $result;

  22. if(!$current_page || $current_page < 0)

  23. $this->page = 1;
  24. else $this->page = $current_page;

  25. if(!emptyempty($results_per_page))

  26. $this->results_per_page = $results_per_page;

  27. $numrows = @mysql_num_rows($this->result);

  28. if(!$numrows) {
  29. echo "查询结果为空.\n";
  30. return;
  31. }

  32. $this->total_pages = ceil($numrows / $this->results_per_page);

  33. }

  34. /*

  35. 下面是打印内容的函数,可以不用,也可以根据自己的需要扩展
  36. 这里只是打印出id
  37. */
  38. function print_paged_results() {
  39. echo "\n";
  40. $start = ($this->page - 1) * $this->results_per_page;
  41. mysql_data_seek($this->result, $start);
  42. $x = 0;
  43. for($i = 1; $i <= $this->results_per_page && $row = @mysql_fetch_array($this->result); $i++) {
  44. if($x++ & 1) $bgcolor = "#F2F2FF";
  45. else $bgcolor = "#EEEEEE";

  46. echo "

  47. ";
  48. // 编辑这部分输出任何您想要的HTML
  49. }
  50. echo "
  51. ". $row["id"] . "
    \n";
  52. }

  53. /*

  54. 下面是打印页码和链接的函数,在需要显示页码的地方调用
  55. */
  56. function print_navigation() {
  57. global $PHP_SELF;
  58. echo "";
  59. for($i = 1; $i <= $this->total_pages; $i++) { #loop to print << 1 2 3... $total_pages >>
  60. if($i == 1 && $this->page > 1) #Prints the << first to goto the previous page (not on page 1)
  61. echo "page - 1)."\" onMouseOver=\"status="Previous Page";return true;\" onMouseOut=\"status=" ";return true;\">?";

  62. if($i == $this->page) #Doesn"t print a link itself, just prints page number

  63. echo " $i ";

  64. if($i != $this->page) #Other links that aren"t this page go here

  65. echo " $i ";

  66. if($i == $this->total_pages && $this->page != $this->total_pages) # Link for next page >> (not on last page)

  67. echo "page + 1)."\" onMouseOver=\"status="Go to the Next Page";return true;\" onMouseOut=\"status=" ";return true;\">?";
  68. }

  69. echo "\n";

  70. }
  71. }

  72. /* 例子 http://bbs.it-home.org

  73. mysql_connect($server, $uname, $pass );
  74. mysql_select_db("$db");
  75. $result= @mysql_query("Select * FROM table");

  76. $p = new mysql_pager( $result, $page=$_GET["page"], 10 );

  77. $p->print_navigation();
  78. $p->print_paged_results();
  79. $p->print_navigation();
  80. */
  81. ?>

人气教程排行