php實現搜索和分頁效果-親測有效


php搜索+分頁,單寫容易,組合起來不容易,網上找了一下,代碼不全,搜索和分頁沒有完全實現,經過自己的修改嘗試,成功實現簡單的搜索+分頁功能。

效果如下:

php實現搜索+分頁

下面是完整的代碼!寫在一個php頁面里面即可!所需要做的修改就是你的數據庫信息和表信息。即可實現上面圖片同樣的效果!感謝網上分享的網友,我在此基礎上改出了自己想要的功能,因此也貼出來,想對有些朋友有幫助。

<?php
$wherelist=array();
$urlist=array();
if(!empty($_GET['id']))
{
$wherelist[]=" id like '%".$_GET['id']."%'";
$urllist[]="id=".$_GET['id'];
 
}
if(!empty($_GET['username']))
{
$wherelist[]=" username like '%".$_GET['username']."%'";
$urllist[]="username=".$_GET['username'];
}if(!empty($_GET['age']))
{
$wherelist[]=" age like '%".$_GET['age']."%'";
$urllist[]="age=".$_GET['age'];
}
$where="";
if(count($wherelist)>0)
{
$where=" where ".implode(' and ',$wherelist);
$url='&'.implode('&',$urllist);
}
//分頁的實現原理
//1.獲取數據表中總記錄數
$mysql_server_name='localhost';
$mysql_username='root';
$mysql_password='root';
$conn=mysql_connect($mysql_server_name,$mysql_username,$mysql_password);
mysql_query("set names 'utf8'");
mysql_select_db("aaa");
$sql="select * from user $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 user {$where} order by id desc {$limit}"; //此處加了id降序
$res=mysql_query($sql1);
?>


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>用戶資料顯示</title>
</head>
<body>
<form action="searchpage.php" method="get">
id:<input type="text" name="id" value="<?php echo $_GET['id']?>" size="8">
用戶名<input type="text" name="username" value="<?php echo $_GET['username']?>" size="8">
年齡:<input type="text" name="age" value="<?php echo $_GET['age']?>" size="8">
 <input type="button" value="查看全部" onclick="window.location='searchpage.php'">
 <input type="submit" value="搜索">
</form>
<br/>
<table border="1" width="500" >
 <tr>
 <td>編號</td>
 <td>用戶名</td>
 <td>年齡</td>
 <td>性別</td>
 <td>電話</td>
 <td>地址</td>
 </tr>
<?php while($row= mysql_fetch_assoc($res)){?>
<tr>
 <td><?php echo $row['id'] ?></td>
 <td><?php echo $row['username'] ?></td>
 <td><?php echo $row['age'] ?></td>
 <td><?php if($row['sex']){echo '男';}else{echo '女';} ?></td>
 <td><?php echo $row['phone'] ?></td>
 <td><?php echo $row['address'] ?></td>
 </tr>
<?php }?>
<tr>
 <td colspan="6">
<?php
 echo " 當前{$page}/{$maxpage}頁 共{$totalnum}條";
echo " <a href='searchpage.php?page=1{$url}'>首頁</a> ";
echo "<a href='searchpage.php?page=".($page-1)."{$url}'>上一頁</a>";
echo "<a href='searchpage.php?page=".($page+1)."{$url}'>下一頁</a>";
echo " <a href='searchpage.php?page={$maxpage}{$url}'>尾頁</a> ";
?>
</td>
 </tr>
</table>
</body>
</html>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM