wangy 发表于 2021-6-20 21:50:23

【PHP教程】PHP模糊查询事例代码

<?php
header("content-type:text/html;charset=utf-8");
//获取用户数据
$keywords=$_POST['keywords'];
//连接数据库
$conn=@mysql_connect('localhost','root','') or die('数据库链接失败');
//选择数据库,设置字符集
mysql_select_db('search');
mysql_set_charset('utf8');
//php模糊查询
if(empty($keywords)){
    $str= "请输入要查询的内容";
}else{
$sql="SELECT * FROM user WHERE username LIKE '%$keywords%'";
}
$rs=mysql_query($sql);
$users = array();
while($row=mysql_fetch_assoc($rs)){
    //高亮替换
    $row['username'] = str_replace($keywords, '<font color="red">'.$keywords.'</font>', $row['username']);
    $users[] = $row;
}
//print_r($users);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>php模糊查询</title>
</head>
<body>
<h1>php模糊查询器之用户查询</h1>
<form action="" method="post">
用户名:<input type="text" name="keywords" placeholder="请输入查询内容"/> <input type="submit" value="提交查询"/>
</form>
<?php
if($keywords){
    echo '<h3>查询关键字<font color="red"> '.$keywords.' </font>结果是:</h3>';
if($users){
    echo "<table width='500px' border='1px' cellpadding='3px' cellspacing=0>";
    echo "<tr bgcolor='#ddd'><th>UID</th><th>用户名</th><th>性别</th><th>邮箱</th><th>兴趣爱好</th></tr>";
    foreach ($users as $key => $value){
      echo "<tr>";
      echo "<td>".$value['uid']."</td>";
      echo "<td>".$value['username']."</td>";
      echo "<td>".$value['sex']."</td>";
      echo "<td>".$value['email']."</td>";
      echo "<td>".$value['hobby']."</td>";
      echo "</tr>";
    }
    echo "</table>";
}else {
    echo "没有查询到相关用户";
}
}else{
   echo "<h4> <font color='red'>".$str."</font></h4><br/>";
}
?>
</body>
</html>
页: [1]
查看完整版本: 【PHP教程】PHP模糊查询事例代码