V 友们下午好.
我现在正在尝试写一个 php 多条件动态查询数据库的页面,但是我现在的代码遇到了问题,访问的时候返回空白
我曾尝试百度 /谷歌过.但是没有得到解决方案
我的接口是类似这样的 baidu.com?one=1&two=2&three=3&four=4
但是有时候我不想查 one 参数,这样的话接口就是 baidu.com?two=2&three=3&four=4
他们每一个字段都有可能不是我想查询的.这样的话代码应该怎么写呢?
V 友们能否给我一些建议呢?
非常感谢!
我的代码是这样写的
1
sun522198558 2023-01-04 15:48:59 +08:00
foreach ($_GET as $key => $value) { }
|
2
ersic 2023-01-04 15:55:18 +08:00
我会这么写
``` <?php $params = $_GET; if ($params) { $where = ''; foreach ($params as $key => $value) { if ($where == '') { $where = "$key = $value"; } else { $where .= "and $key = $value"; } } $sql = "SELECT * FROM table where " . $where; } ``` |
3
gesse 2023-01-04 15:58:23 +08:00
|
4
8355 2023-01-04 16:21:04 +08:00
代码相当之哇塞啊
|
5
tomczhen 2023-01-04 16:23:54 +08:00 via Android
SQL 注入了解一下。
|
6
herozzm 2023-01-04 16:29:31 +08:00
完全过滤,等着被黑
|
7
pota 2023-01-04 16:31:08 +08:00
😂 别这么写,SQL 注入分分钟就没了,用个简单点的 ORM 吧
|
8
hgc81538 2023-01-04 16:50:41 +08:00
即時寫的, 未測試
``` <?php $one = isset($_GET['one']) ? filter_var($_GET['one']) : null; $two = isset($_GET['two']) ? filter_var($_GET['two']) : null; $three = isset($_GET['three']) ? filter_var($_GET['three']) : null; $four = isset($_GET['four']) ? filter_var($_GET['four']) : null; $wheres = []; $params = []; if($one !== null){ $wheres[] = "`one` = ?"; $params[] = $one; } if($two !== null){ $wheres[] = "`two` = ?"; $params[] = $two; } if($three !== null){ $wheres[] = "`three` = ?"; $params[] = $three; } if($four !== null){ $wheres[] = "`four` = ?"; $params[] = $four; } $sql = 'select * from `table`'; if($wheres){ $sql .= ' where '.implode(' and ', $wheres); } $mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world'); $stmt = $mysqli->prepare($sql); if($wheres){ $stmt->bind_param(implode('', array_fill(0, count($wheres), 's')), ...$params); } $stmt->execute(); ``` |
9
spicy777 2023-01-04 16:51:43 +08:00
你库没有了 /doge
|
10
cbasil 2023-01-10 13:15:41 +08:00
<pre>
<?php $one = addslashes($_GET['one']); $two = addslashes($_GET['two']); $three = addslashes($_GET['three']); $four = addslashes($_GET['four']); $where = '1 = 1'; if($one) $where .= " and `one` = '$none'"; if($two) $where .= " and `two` = '$two'"; $sql = "SELECT * FROM table whre ".$where; </pre> 简单的过滤一下, |
11
zhanshen1614 2023-01-16 18:41:31 +08:00
WHERE 后面加上 1=1 ,用 PDO ,遍历请求参数数组来实现多条件动态查询。
|