分页类的封装如下:
page.php
<?php
//showPage(页号,总页数,分隔符)
function showPage($page,$totalPage,$sep=" "){
$url = $_SERVER ['PHP_SELF']; //获取当前路径
$index = ($page == 1) ? "首页" : "<a href='{$url}?page=1'>首页</a>";
$last = ($page == $totalPage) ? "尾页" : "<a href='{$url}?page={$totalPage}'>尾页</a>";
$prevPage=($page>=1)?$page-1:1;
$nextPage=($page>=$totalPage)?$totalPage:$page+1;
$prev = ($page == 1) ? "上一页" : "<a href='{$url}?page={$prevPage}'>上一页</a>";
$next = ($page == $totalPage) ? "下一页" : "<a href='{$url}?page={$nextPage}'>下一页</a>";
$str = "总共{$totalPage}页/当前是第{$page}页";
$p="";
for($i = 1; $i <= $totalPage; $i ++) {
//当前页无连接
if ($page == $i) {
$p .= "[{$i}]";
} else {
$p .= "<a href='{$url}?page={$i}'>[{$i}]</a>";
}
}
$pageStr=$str.$sep . $index .$sep. $prev.$sep . $p.$sep . $next.$sep . $last;
return $pageStr; //返回分页字符串
---------------------
一个调用分页类的例子
userlist.php
<?php
include "../mysql.php";
include "../page.php";
//连接数据库
$conn=new Mysql();
//
$pageSize=2; //每页显示的记录数
$sql="select * from user;";
$totalRows=$conn->getResultNum($sql); //总记录数
$totalPage=ceil($totalRows/$pageSize); //总页数
$page=isset($_REQUEST['page'])?(int)$_REQUEST['page']:1;//当前页数
if($page<1||$page==null||!is_numeric($page)){
$page=1;
}
if($page>=$totalPage)$page=$totalPage;
$offset=($page-1)*$pageSize;
$sql="select * from user limit {$offset},{$pageSize}";
$result=$conn->sql($sql);
echo "<table style='text-align: center'>";
echo "<tr><td>用户名</td><td>密码</td><td>性别</td><td>邮箱</td></tr>";
foreach ($result as $k=>$v)
{
echo "<tr><td>{$v['name']}</td>";
echo "<td>"."{$v['password']}"."</td>";
echo "<td>{$v['sex']}</td>";
echo "<td>{$v['email']}</td></tr>";
}
echo "</table>";
echo showPage($page,$totalPage); //输出页码链接
echo"<hr/>";
//关闭数据库
$conn->close();
运行结果:
数据库的封装之前写过,这里不在赘述
数据库封装:http://blog.csdn.net/c_jian/article/details/52847499
---------------------
作者:不能吃的坚果
来源:CSDN
原文:https://blog.csdn.net/C_jian/article/details/52944888
版权声明:本文为博主原创文章,转载请附上博文链接!