本节分享一个php、mysql分页类,代码如下:
<?php /**** 文件名 : pagination.class.php 功 能 : php mysql 分页类 ****/ class pagination { var $fullresult; // 数据库中整个记录的结果集 var $totalresult; // 总记录数 var $query; // 用户查询 var $resultPerPage; // 每页显示的记录数 var $resultpage; // 每一页的记录集 var $pages; // 总页数 var $openPage; // 当前页 /* @param - 查询语句 @param - 每页记录数 */ function createPaging($query,$resultPerPage) { $this->query = $query; $this->resultPerPage= $resultPerPage; $this->fullresult = mysql_query($this->query); $this->totalresult = mysql_num_rows($this->fullresult); $this->pages = $this->findPages($this->totalresult,$this->resultPerPage); if(isset($_GET['page']) && $_GET['page']>0) { $this->openPage = $_GET['page']; if($this->openPage > $this->pages) { $this->openPage = 1; } $start = $this->openPage*$this->resultPerPage-$this->resultPerPage; $end = $this->resultPerPage; $this->query.= " LIMIT $start,$end"; } elseif($_GET['page']>$this->pages) { $start = $this->pages; $end = $this->resultPerPage; $this->query.= " LIMIT $start,$end"; } else { $this->openPage = 1; $this->query .= " LIMIT 0,$this->resultPerPage"; } $this->resultpage = mysql_query($this->query); } /* @param - 总记录数 @param - 每页记录数 */ function findPages($total,$perpage) { $pages = intval($total/$perpage); if($total%$perpage > 0) $pages++; return $pages; } /* 显示分页 */ function displayPaging() { $self = $_SERVER['PHP_SELF']; if($this->openPage<=0) { $next = 2; } else { $next = $this->openPage+1; } $prev = $this->openPage-1; $last = $this->pages; if($this->openPage > 1) { echo "<a href=$self?page=1>First</a>  "; echo "<a href=$self?page=$prev>Prev</a>  "; } else { echo "First  "; echo "Prev  "; } for($i=1;$i<=$this->pages;$i++) { if($i == $this->openPage) echo "$i  "; else echo "<a href=$self?page=$i>$i</a>  "; } if($this->openPage < $this->pages) { echo "<a href=$self?page=$next>Next</a>  "; echo "<a href=$self?page=$last>Last</a>  "; } else { echo "Next  "; echo "Last  "; } } } ?>
调用示例:
<?php /*** 文件名称 : showresult.php 功 能 : 显示分页结果 ***/ include_once("pagination.class.php"); // 调用分页类 $pagination = new pagination(); $query = "SELECT * FROM `student` WHERE 1"; // 查询语句 /* 调用方法,创建分页 @param - 数据库查询 @param - 每页显示的记录数 */ $pagination->createPaging($query,10); echo '<table border="1" width="400" align="center">'; while($row=mysql_fetch_object($pagination->resultpage)) { echo '<tr><td>'.$row->name.'</td><td>'.$row->age.'</td></tr>'; // display name and age from database } echo '</table>'; echo '<table border="1" width="400" align="center">'; echo '<tr><td>'; $pagination->displayPaging(); echo '</td></tr>'; echo '</table>'; ?>