php分页原理简单分页代码总结

发布时间:2019-12-23编辑:脚本学堂
有关php分页代码的实现原理,一个php分页的小例子,每页显示记录数,判断当前页数,不错的入门级php分页代码,需要的朋友参考下。

尝试自己写一个php分页代码,从网上找了很多资料,代码都太复杂,这里以一个简单的php分页代码实例,学习下php的分页原理

专题推荐:php分页代码大全

例子:
 

复制代码 代码示例:

//定每页显示多少条
//count(*)查询总条数
//计算总页数ceil()
//判断$_GET 并赋值当前页数
//mysql查询 limit (当前页数-1)*每页条数,每页条数
//如果总条数不为空,进行循环mysql_fetch_array()
//$_SERVER['PHP_SELF']
//上一页?page=当前页-1
//下一页?page=当前页+1
//edit: www.jb200.com
<?php
include("conn.php");
$perpagenum = 3;
$total = mysql_fetch_array(mysql_query("SELECT COUNT(*) FROM message"));
$Total = $total[0];
$Totalpage =ceil($Total/$perpagenum);

if(!isset($_GET['page'])||!intval($_GET['page'])||$_GET['page']>$Totalpage){
    $page = 1;
}else{
    $page = $_GET['page'];
}

$start = ($page-1)*$perpagenum;
$sql = "SELECT * FROM message ORDER BY id DESC LIMIT $start,$perpagenum";
$result = mysql_query($sql);
$contents = mysql_fetch_array($result);
?>
<table width="849" height="90">
<?php
if($total){
    do{
   $user = $contents['user'];
   $contact = $contents['contact'];
   $content = $contents['content'];
   $date    = $contents['date'];

?>
<tr bgcolor="#B3DBB5">
<td width="193" height="22">昵称:<?php echo $user;?></td>
<td width="373"><?php echo $contact;?></td>
<td width="261">发表于:<?php echo $date;?></td>
</tr>
<tr bgcolor="#D8D8D8">
<td height="auto" colspan="3"><?php echo $content;?></td>
</tr>
<?php
 }
//php分页开始
while($contents=mysql_fetch_array($result));
$per = $page-1;
$next= $page+1;
echo "<center>共有".$Total."条留言,每页".$perpagenum."条,共".$page."/".$Totalpage."页。";
if($page!=1){
 echo "<a href=".$_SERVER['PHP_SELF'].">首页</a>".
"<a href=".$_SERVER['PHP_SELF']."?page=$per".">上一页</a>";
}
if($page!=$Totalpage){
 echo "<a href=".$_SERVER['PHP_SELF']."?page=$next".">下一页</a>";
echo "<a href=".$_SERVER['PHP_SELF']."?page=$Totalpage".">尾页</a>";
}
?>
<?php
}
?>
</table>