課程代碼:
<?php
$keywrods=isset($_GET['keywrods'])?trim($_GET['keywrods']):'';
$conn=@mysql_connect('127.0.0.3','root','root')or die('連接失敗');
mysql_query('use user');//選擇數據庫
mysql_query('set names utf8');//設置字符編碼
//關鍵詞
$sql="select * from user where username like '%{$keywrods}%'";
$rs=mysql_query($sql);//查詢結果集
$users=array();//用這個數組保存查詢到的數據
if(!empty($keywrods)){//判斷傳入的數據不為空時,才執行while
while ($row=mysql_fetch_assoc($rs)) {
//對用戶名進行關鍵詞高亮
$row['username']=str_replace($keywrods, '<font color="red">'.$keywrods.'</font>',$row['username']);
$users[]=$row;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>搜索</title>
</head>
<body>
<h1>PHP模糊查詢</h1>
<form action="" method="get">
用戶名: <input type="text" name="keywrods" value="" />
<input type="submit" value="查詢" />
</form>
<?php
if($keywrods){
echo '<h3>查詢關鍵詞<font color="red">'.$keywrods.'</font>的結果</h3>';
}
if($users){
echo '<table width="500" border="1" cellpadding="5">';
echo '<tr bgcolor="orange"><th>用戶名:</th><th>郵箱地址:</th><th>性別:</th><th>愛好:</th></tr>';
foreach ($users as $k => $v) {
echo '<tr>';
echo '<td>'.$v['username'].'</td>';
echo '<td>'.$v['email'].'</td>';
echo '<td>'.$v['sex'].'</td>';
echo '<td>'.$v['hobby'].'</td>';
echo '</tr>';
}
echo '</table>';
}else{
echo "沒有查詢到相關用戶";
}
?>
</body>
</html>
東寫西讀
2014-11-04
0 回答
舉報
0/150
提交
取消