PHP搜索与分页功能实现详解
处理海量数据时,采用分页展示是常见的解决方案。许多初学者对此感到困惑,因此本文将深入解析其背后的逻辑与具体实现步骤,帮助读者彻底掌握分页显示的核心原理及编码技巧。
文中提供的所有示例程序均基于PHP语言开发。
分页显示的本质,是将数据库查询返回的结果集进行人工切分,以便逐段呈现给用户。
建议仔细阅读下方代码,亲自调试运行,并尝试在此基础上添加自定义功能以加深理解。
$wherelist=array();
$urlist=array();
if(!empty($_GET['title']))
{
$wherelist[]=" title like '%".$_GET['title']."%'";
$urllist[]="title=".$_GET['title'];
}
if(!empty($_GET['keywords']))
{
$wherelist[]=" keywords like '%".$_GET['keywords']."%'";
$urllist[]="keywords=".$_GET['keywords'];
}if(!empty($_GET['author']))
{
$wherelist[]=" author like '%".$_GET['author']."%'";
$urllist[]="author=".$_GET['author'];
}
$where="";
if(count($wherelist)>0)
{
$where=" where ".implode(' and ',$wherelist);
$url='&'.implode('&',$urllist);
}
//分页的实现原理
//1.获取数据表中总记录数
$sql="select count(*) from news $where ";
$result=mysql_query($sql);
$totalnum=mysql_num_rows($result);
//每页显示条数
$pagesize=5;
//总共有几页
$maxpage=ceil($totalnum/$pagesize);
$page=isset($_GET['page'])?$_GET['page']:1;
if($page <1)
{
$page=1;
}
if($page>$maxpage)
{
$page=$maxpage;
}
$limit=" limit ".($page-1)*$pagesize.",$pagesize";
$sql1="select * from news {$where} {$limit}";
//$sql1="select * from news {$where} {$limit}";
$res=mysql_query($sql1);
?>
<form action="searchpage.php" method="get">
标题:<input type="text" name="title" value="<?php echo $_GET['title']?>" size="8">
关键字<input type="text" name="keywords" value="<?php echo $_GET['keywords']?>" size="8">
作者:<input type="text" name="author" value="<?php echo $_GET['author']?>" size="8">
<input type="button" value="查看全部" onclick="window.location='searchpage.php'">
<input type="submit" value="搜索">
</form>
编号
标题
关键字
作者
日期
内容
<?php while($row= mysql_fetch_assoc($res)){?>
<?php echo $row['id'] ?>
<?php echo $row['title'] ?>
<?php echo $row['keywords'] ?>
<?php echo $row['author'] ?>
<?php echo date("Y-m-d H:i:s",$row['addtime']) ?>
<?php echo $row['content'] ?>
<?php }?>
<?php
echo " 当前{$page}/{$maxpage}页 共{$totalnum}条";
echo " 首页 ";
echo "上一页";
echo "下一页";
echo " 尾页 ";
?>
期望这些内容能为各位的PHP开发工作带来实质性的帮助。