PHP 多条件动态查询数据库要怎么写

2023-01-04 15:44:52 +08:00
 lsrnb

V 友们下午好.
我现在正在尝试写一个 php 多条件动态查询数据库的页面,但是我现在的代码遇到了问题,访问的时候返回空白
我曾尝试百度 /谷歌过.但是没有得到解决方案
我的接口是类似这样的 baidu.com?one=1&two=2&three=3&four=4
但是有时候我不想查 one 参数,这样的话接口就是 baidu.com?two=2&three=3&four=4
他们每一个字段都有可能不是我想查询的.这样的话代码应该怎么写呢?
V 友们能否给我一些建议呢?
非常感谢!
我的代码是这样写的

1800 次点击
所在节点    PHP
12 条回复
sun522198558
2023-01-04 15:48:59 +08:00
foreach ($_GET as $key => $value) { }
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;
}

```
gesse
2023-01-04 15:58:23 +08:00
8355
2023-01-04 16:21:04 +08:00
代码相当之哇塞啊
tomczhen
2023-01-04 16:23:54 +08:00
SQL 注入了解一下。
herozzm
2023-01-04 16:29:31 +08:00
完全过滤,等着被黑
pota
2023-01-04 16:31:08 +08:00
😂 别这么写,SQL 注入分分钟就没了,用个简单点的 ORM 吧
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();

```
spicy777
2023-01-04 16:51:43 +08:00
你库没有了 /doge
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>
简单的过滤一下,
zhanshen1614
2023-01-16 18:41:31 +08:00
WHERE 后面加上 1=1 ,用 PDO ,遍历请求参数数组来实现多条件动态查询。
zero3412
2023-01-30 22:57:58 +08:00
@spicy777 都是这么过来的嘛😊

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/906542

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX