- 目录
- 1.前言
- 2.案例讲解
- 2.1查询以某个字符开头的用户
- 2.2查询以某个字符结尾的用户
- 2.3查询包含某个字符的用户
- 2.4查询与限定用户长度匹配的用户
- 2.5两种通配符的结合使用
- 3. 查询案例
- 3.1演示代码
- 3.2查询搜素之关键词变色
1.前言
模糊查询原理,本质上是对sql语句的查询操作;使用sql匹配模式,只能使用操作符LINK或者NOT LINK;并且提供了两种通配符%表示任意数量的任意字符(其中包括0个)以及_表示的任意单个字符;如果匹配格中不包含以上两种通配符的任意一个,其中查询的效果等同于=或者!=
2.案例讲解
2.1查询以某个字符开头的用户
查询以符号l开头的用户:select*from user where username like 'l%';
2.2查询以某个字符结尾的用户
查询符号e结尾的用户:select*from user where username like '%e';
2.3查询包含某个字符的用户
比如,查询用户名包含字符'0'的用户:select*from user where username like '%0%';
2.4查询与限定用户长度匹配的用户
查询用户长度为3的用户:select*from user where username like '___';
2.5两种通配符的结合使用
查询用户名第二个字符为o的用户:select*from user where username like '_O%';
3.查询案例
3.1基本查询演示代码
<?php $keywords = isset($_GET['keywords']) ? trim($_GET['keywords']) : ''; $conn = mysqli_connect("localhost", "root", "root") or die("数据库链接错误"); mysqli_select_db( $conn,'myyaf'); mysqli_query($conn,"set names 'utf8'"); //使用utf-8中文编码; //PHP模糊查询 $sql="SELECT * FROM t_user WHERE name LIKE '%{$keywords}%'"; $rs= mysqli_query($conn,$sql); $users = array();//保存所以得查询到的用户 if(!empty($keywords)){ while ($row=mysqli_fetch_assoc($rs)){ $users[] = $row; } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>查询器</title> <style> .textbox { width: 355px; height: 40px; border-radius: 3px; border: 1px solid #e2b709; padding-left: 10px; } .su { width: 365px; height: 40px; background-color: #7fbdf0; color: white; border: 1px solid #666666; } table{ background-color: #7fbdf0; line-height:25px;} th{ background-color:#fff;} td{ background-color:#fff; text-align:center} </style> </head> <body > <form action="" method="get"> <p><input type="text" name="keywords" class="textbox" value="" placeholder="请输入内容"/> <p><input type="submit" class="su" value="查询"/> </form> <?php if ($keywords){ echo '<h3>查询关键词:<font color="red">'.$keywords.'</font></h3>'; } if ($users){ echo '<table width="500" cellpadding="5" >'; echo '<tr><th>用户名</th><th>密码</th><th>手机</th>'; foreach ($users as $key=>$value){ echo '<tr>'; echo '<td>'.$value['name'].'</td>'; echo '<td>'.$value['password'].'</td>'; echo '<td>'.$value['mobilephone'].'</td>'; echo '</tr>'; } }else{ echo '没有查询到相关用户'; } ?> </body> </html>
效果如下图所示:
3.2查询搜素之关键词变色
上一节我们已经基本完成了如何搜索关键词,我们接下来对搜索显示做美化。
在模糊查询语句中加入下面你的代码
$row['username']=str_replace($keywords,'<font color="red">'.$keywords.'</font>',$row['username']);
他的意思是把查询的名字中查询的关键词替换成红色的字体。
具体代码块:
if(!empty($keywords)){ while ($row=mysqli_fetch_assoc($rs)){ $row['name'] = str_replace($keywords,'<font color="red">'.$keywords.'</font>',$row['name']); $users[] = $row; } }
其余代码与小结3.1一样,效果如下图所示: