PHP 简单分页

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>人员信息</title>

<?php

function page($pageNum = 1,$pageSize=3){
//1. 链接数据库
$conn = @new mysqli("127.0.0.1","root","123");

if($conn->connect_errno){ //返回链接错误号
//返回链接错误信息
die("数据库链接失败:".$conn->connect_error);
}

//2. 选择数据库
$conn->select_db("collect") or die("选择数据库失败:".$conn->error);

//3.设置字符集编码
$conn->set_charset("utf8") or die("设置字符集失败:".$conn->error);

//4. 准备SQL语句
$sql = "select * from page limit " . (($pageNum - 1) * $pageSize) . "," . $pageSize;
//5. 执行SQL语句,返回结果集或者布尔类型true/false
$res = $conn->query($sql);
$ress = array();
while( $row = $res->fetch_array()) {
$ress[] = $row;
}
$res->close();
$conn->close();
return $ress;
}

function allpage(){
//1. 链接数据库
$conn = @new mysqli("127.0.0.1","root","123");

if($conn->connect_errno){ //返回链接错误号
//返回链接错误信息
die("数据库链接失败:".$conn->connect_error);
}

//2. 选择数据库
$conn->select_db("collect") or die("选择数据库失败:".$conn->error);

//3.设置字符集编码
$conn->set_charset("utf8") or die("设置字符集失败:".$conn->error);

//4. 准备SQL语句
$sql = "select count(*) num from page";
//5. 执行SQL语句,返回结果集或者布尔类型true/false
$res = $conn->query($sql);
$obj = mysqli_fetch_object($res);
$res->close();
$conn->close();
return $obj->num;
}
$allNum = allpage();
//规定一页显示几个人员信息
$pageSize = 3;
//分页
$pageNum = empty($_GET["pageNum"])?1:$_GET["pageNum"];
$endPage = ceil($allNum/$pageSize); //总页数
$array = page($pageNum,$pageSize);



?>
</head>
<body>
<table cellspacing="0" cellpadding="1" width="500" border="1" style="text-align: center">
<tr>
<th>编号</th>
<th>姓名</th>
<th>年龄</th>
</tr>
<?php
foreach ($array as $v){
echo "<tr>";
echo "<td>{$v['id']}</td>";
echo "<td>{$v['name']}</td>";
echo "<td>{$v{'age'}}</td>";
echo "</tr>";
}
?>
</table>
<div>
<a href="?pageNum=1">首页</a>
<a href="?pageNum=<?php echo $pageNum==1?1:($pageNum-1)?>">上一页</a>
<a href="?pageNum=<?php echo $pageNum==$endPage?$endPage:($pageNum+1)?>">下一页</a>
<a href="?pageNum=<?php echo $endPage?>">尾页</a>

</div>

</body>
</html>

 


posted @ 2019-02-13 12:57  isafer_wilson  阅读(169)  评论(0编辑  收藏  举报