PHP mysql实现搜索功能
程序员文章站
2022-03-01 17:40:56
...
实例
<?php //显示所有数据 //var_dump($_GET); //搜索开始 如果存在我们就拼接一个where条件即可 $where = ''; if (!empty($_GET['name'])) { //$where = " WHERE name LIKE '%".$_GET['name']."%' "; $where[] = "name LIKE '%{$_GET['name']}%'"; } if(!empty($_GET['age'])){ $where[]= "age = {$_GET['age']}"; } if (!empty($_GET['city'])) { $where[] = "city LIKE '%{$_GET['city']}%'"; } //var_dump($where); if(!empty($where)){ $where =' WHERE '.implode(' and ',$where); } //echo $where; //echo $where; $link = mysqli_connect('localhost','root','123456'); if (mysqli_connect_errno($link)>0) { echo mysqli_connect_error($link);exit; } mysqli_select_db($link,'ss34'); mysqli_set_charset($link,'utf8'); $sql="SELECT id,name,sex,age,city FROM info {$where}"; $result = mysqli_query($link,$sql); if ($result && mysqli_num_rows($result)>0) { //声明一个新数组 $userlist = array(); while($row = mysqli_fetch_assoc($result)){ $userlist[]=$row; } } //var_dump($userlist); //定义一个变量用来声明编号 $i=1; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <h3><a href="add.html">添加用户</a></h3> <!-- 如果你要做搜索内容 method="get" --> <form action="index.php" method="get"> 姓名: <input type="text" name="name"> 年龄: <input type="text" name="age"> <input type="submit" value="搜索"> </form> <hr> <table border="1" width="800" align="center"> <caption><h3>学员管理系统v1.0</h3></caption> <tr> <th>编号</th> <th>姓名</th> <th>年龄</th> <th>性别</th> <th>城市</th> <th>操作</th> </tr> <?php if(!empty($userlist)){?> <?php foreach($userlist as $value){?> <tr> <td><?php echo $i++?></td> <td><?php echo $value['name']?></td> <td><?php echo $value['age']?></td> <td> <?php $sex = $value['sex']; switch($sex){ case 0: echo '女'; break; case 1: echo '男'; break; case 2: echo '保密'; break; case 3: echo '琦琦'; break; default: echo '人妖'; } ?> </td> <td><?php echo $value['city']?></td> <td><a href="./del.php?id=<?php echo $value['id']?>" onclick="return confirm('数据无价 谨慎操作')">删除</a>|<a href="edit.php?id=<?php echo $value['id']?>">修改</a></td> </tr> <?php } ?> <?php }else{?> <tr><td colspan="6">暂无数据</td></tr> <?php }?> </table> </body> </html>
运行实例 »
点击 "运行实例" 按钮查看在线实例