Talk is cheap,show the code like this.少废话,放码过来。
1.连接Mysql服务器,选择数据库,设定字符集;
<?php
//声明网页字符集
header("Content-Type:text/html;charset=utf-8");
//数据库配置信息
$db_host='localhost'; //主机名
$db_port='3306'; //端口号
$db_user='root'; //用户名
$db_pass='root'; //密码
$db_name='itcast'; //数据库名称
$charset='utf8'; //字符集
//PHP连接MySQL服务器
if(!$link=@mysql_connect($db_host.":".$db_port,$db_user,$db_pass))
die("PHP连接MySQL服务器失败!");
//选择数据库
if(!mysql_select_db($db_name))
die("选择数据库{$db_name}失败!");
mysql_query("set names {$charset}");
?>
2.取出数据并进行分页操作:
<?php
header("content-type:text/html;charset=utf-8");
require_once("conn.php");
//1.每页显示条数
$pagesize=2;
// 2.获取当前页码和计算当前行号
$page=isset($_GET['page'])?$_GET['page']:1;
$startrow=($page-1)*$pagesize;
//3.获取总记录数和总页数
$sql="select * from student";
$result=mysql_query($sql);
$records=mysql_num_rows($result);
$pages=ceil($records/$pagesize);
$sql="select * from student order by id desc limit {$startrow},{$pagesize}";
// echo $sql."<br>";
// echo $pages;
$result=mysql_query($sql);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>学生信息管理中心</title>
<style>
tr a{
display:inline-block;
padding:0px 5px;
text-decoration:none;
border:solid 1px #ccc;
margin:0px 3px;
}
tr a:link,a:visited{
color:blue;
}
tr a:hover{
background:#888;
}
tr span{
padding:0px 5px;
}
</style>
</head>
<body>
<div align="center">
<h2>学生信息管理</h2>
</div>
<table width="500" align="center" cellspacing="0" border="1">
<tr align='center'>
<th>编号</th>
<th>姓名</th>
<th>性别</th>
<th>年龄</th>
<th>学历</th>
<th>工资</th>
<th>奖金</th>
<th>籍贯</th>
</tr>
<?php
while($arr=mysql_fetch_assoc($result))
{
?>
<tr align="center">
<td><?php echo $arr['id'] ?></td>
<td><?php echo $arr['name'] ?></td>
<td><?php echo $arr['sex'] ?></td>
<td><?php echo $arr['age'] ?></td>
<td><?php echo $arr['edu'] ?></td>
<td><?php echo $arr['salary'] ?></td>
<td><?php echo $arr['bonus'] ?></td>
<td><?php echo $arr['city'] ?></td>
</tr>
<?php
}
?>
<tr align="center">
<td colspan="8">
<?php
//计算循环的起始页和终止页
$start=$page-5;
$end=$page+4;
//如果$page<6时
if($page<6)
{$start=1;
$end=10;}
//如果$page>$pages-4时
if($page>$pages-4)
{$start=$pages-9;
$end=$pages;}
//当总页数不够10页数时
if($pages<10)
{$start=1;
$end=$pages;}
for($i=$start;$i<=$end;$i++)
{
if($i==$page)
{echo "<span>$i</span>";}
else{echo "<a href='?page=$i'>{$i}</a>";}
}
?>
</td>
</tr>
</table>
</body>
</html>
效果图展示:
可以看出虽有基本的分页实现,但结果却差强人意。改善的版本请看《PHP实现分页效果2》。虽然此篇发得晚,但实际上这个是最初实现。