<?php
header("Content-type:text/html;charset=utf-8");
$pageSize = 10;
//接收传入的分页码
$page = $_GET['p'];
//获取分页数据
$host = "localhost";
$username = "root";
$password = "";
$db = "lian";
$conn = mysql_connect($host,$username,$password);
if(!$conn){
echo "连接错误";
exit;
}
mysql_select_db($db);
mysql_query("SET NAMES UTF8");
$sql= "select from page LIMIT ".(($page-1)$pageSize).",".$pageSize;
$result = mysql_query($sql);
echo "<table border=1 cellspacing=0 width=40%>";
echo "<tr><td>id</td><td>name</td></tr>";
while($row = mysql_fetch_assoc($result)){
echo "<tr>";
echo "<td>".$row['id']."</td>";
echo "<td>".$row['name']."</td>";
echo "</tr>";
}
echo "</table>";
mysql_free_result($result);
$total_sql = "SELECT COUNT(*) FROM page";
$total_result = mysql_fetch_array(mysql_query($total_sql));
$total = $total_result[0];
$total_pages = ceil($total/$pageSize);
$showPage = 7;
$pageOffset = ($showPage-1)/2;
$start = 1;
$end = $total_pages;
mysql_close($conn);
//显示数据和分页
$page_banner = "";
if($page > 1){
$page_banner = "<a href='".$_SERVER['PHP_SELF']."?p=1'>首页</a>";
$page_banner .= "<a href='".$_SERVER['PHP_SELF']."?p=".($page-1)."'>上一页</a>";
}
if($total_pages > $page){
if($page > ($pageOffset+1)&&$page < ($total_pages-2)){
$start = $page - $pageOffset;
$end = $page + $pageOffset;
}else if($page <= ($pageOffset+1)){
$start = 1;
$end = 7;
}else{
$start = $total_pages-6;
$end = $total_pages;
}
}else{
$start = 1;
$end = $total_pages;
}
for($i = $start;$i<=$end;$i++){
if($page == $i){
$page_banner .= "<span style='color:red'>".$i."</span>";
}else{
$page_banner .= "<a href='".$_SERVER['PHP_SELF']."?p=".$i."'>".$i."</a>";
}
}
if($page < $total_pages){
$page_banner .= "<a href='".$_SERVER['PHP_SELF']."?p=".($page+1)."'>下一页</a>";
$page_banner .= "<a href='".$_SERVER['PHP_SELF']."?p=".($total_pages)."'>尾页</a>";
}
$page_banner .="共有".$total_pages."页";
$page_banner .="<form action='page.php' method='get'>";
$page_banner .="到第<input type='text' name='p' size='2'>页去";
$page_banner .="<input type='submit' value='确定'>";
$page_banner .="</form>";
echo $page_banner;
?>
总结:
1,接收传入的显示页面指令参数($page)
2,连接数据库利用sql语句从数据库取出数据,主要是select * from 表名 limit 开始位置,每页显示的条数
其中要注意limit后一定要放一个空格
3,从数据库查出总条数,ceil()函数操作总条数/每页显示的条数计算出总页数,其中ceil()是向上取整
4,前一页是$page-1,后一页是$page+1,首页是1,尾页是总页数
5,跳转到哪一页用一个表单传参即可
6,最重要的是显示页码,根据一个页面中显示几个页码、偏移量、总页数和一个页面中显示的页码数比较从而确定
页面中显示的第一个页码和最后一个页码,遍历输出所有要显示的页码。
共同学习,写下你的评论
评论加载中...
作者其他优质文章