php+mysql 进行分页案例

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>分页</title>
<?php

//分页的函数
function news($pageNum = 1, $pageSize = 3)
{
$array = array();
$coon = mysqli_connect("localhost", "root","12345678");
mysqli_select_db($coon, "test");
// limit为约束显示多少条信息,后面有两个参数,第一个为从第几个开始,第二个为长度
$rs = "select * from page limit " . (($pageNum - 1) * $pageSize) . "," . $pageSize;
$r = mysqli_query($coon, $rs);
while ($obj = mysqli_fetch_object($r)) {
$array[] = $obj;
}
mysqli_close($coon,"test");
return $array;
}

//显示总页数的函数
function allNews()
{
$coon = mysqli_connect("localhost", "root","12345678");
mysqli_select_db($coon, "test");
mysqli_set_charset($coon, "utf8");
$rs = "select count(*) num from page"; //可以显示出总页数
$r = mysqli_query($coon, $rs);
$obj = mysqli_fetch_object($r);
mysqli_close($coon,"test");
return $obj->num;
}

@$allNum = allNews();
@$pageSize = 3; //约定每页显示几条信息
@$pageNum = empty($_GET["pageNum"])?1:$_GET["pageNum"];
@$endPage = ceil($allNum/$pageSize); //总页数
@$array = news($pageNum,$pageSize);
?>
</head>
<body>
<table width="163" border="1" cellpadding="0" style="text-align: center">
<tr>
<td>ID</td>
<td>NAME</td>
</tr>
<?php
foreach($array as $key=>$values){
echo "<tr>";
echo "<td>{$values->ID}</td>";
echo "<td>{$values->NAME}</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-07-05 14:31  2538  阅读(297)  评论(0编辑  收藏  举报