二、主要代碼解析
$pagesize=10; //設定每一頁顯示的記錄數
$conn=mysql_connect("localhost","root",""); //串連資料庫
$rs=mysql_query("select count(*) from tb_product",$conn); //取得記錄總數$rs
$myrow = mysql_fetch_array($rs);
$numrows=$myrow[0];
//計算總頁數
$pages=intval($numrows/$pagesize);
//判斷頁數設定
if (isset($_GET['page'])){
$page=intval($_GET['page']);
}
else{
$page=1; //否則,設定為第一頁
}
三、建立用例用表myTable
create table myTable
(id int NOT NULL auto_increment,news_title varchar(50),
news_cont text,add_time datetime,PRIMARY KEY(id))
四、完整代碼
<html>
<head>
<title>php分頁樣本</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
</head>
<body>
<?php
$conn=mysql_connect("localhost","root","");
//設定每一頁顯示的記錄數
$pagesize=1;
mysql_select_db("mydata",$conn);
//取得記錄總數$rs,計算總頁數用
$rs=mysql_query("select count(*) from tb_product",$conn);
$myrow = mysql_fetch_array($rs);
$numrows=$myrow[0];
//計算總頁數
$pages=intval($numrows/$pagesize);
if ($numrows%$pagesize)
$pages++;
//設定頁數
if (isset($_GET['page'])){
$page=intval($_GET['page']);
}
else{
//設定為第一頁
$page=1;
}
//計算記錄位移量
$offset=$pagesize*($page - 1);
//讀取指定記錄數
$rs=mysql_query("select * from myTable
order by id desc limit $offset,$pagesize",$conn);
if ($myrow = mysql_fetch_array($rs))
{
$i=0;
?>
<table border="0" width="80%">
<tr>
<td width="50%" bgcolor="#E0E0E0">
<p align="center">標題</td>
<td width="50%" bgcolor="#E0E0E0">
<p align="center">發布時間</td>
</tr>
<?php
do {
$i++;
?>
<tr>
<td width="50%"><?=$myrow["news_title"]?></td>
<td width="50%"><?=$myrow["news_cont"]?></td>
</tr>
<?php
}
while ($myrow = mysql_fetch_array($rs));
echo "</table>";
}
echo "<div align='center'>共有".$pages."頁(".$page."/".$pages.")";
for ($i=1;$i< $page;$i++)
echo "<a href='fenye.php?page=".$i."'>[".$i ."]</a> ";
echo "[".$page."]";
for ($i=$page+1;$i<=$pages;$i++)
echo "<a href='fenye.php?page=".$i."'>[".$i ."]</a> ";
echo "</div>";
?>
</body>
</html>
五、總結
本例代碼在windows2000 server+php4.4.0+mysql5.0.16上運行正常。該樣本顯示的分頁格式是[1][2][3]…這樣形式。假如想顯示成“首頁 上一頁 下一頁 尾頁”這樣形式,請加入以下代碼:
$first=1;
$prev=$page-1;
$next=$page+1;
$last=$pages;
if ($page > 1)
{
echo "<a href='fenye.php?page=".$first."'>首頁</a> ";
echo "<a href='fenye.php?page=".$prev."'>上一頁</a> ";
}
if ($page < $pages)
{
echo "<a href='fenye.php?page=".$next."'>下一頁</a>
echo "<a href='fenye.php?page=".$last."'>尾頁</a> ";
}
其實,寫分頁顯示代碼是很簡單的,只要掌握了它的工作原理。