duanlian1978 2019-08-12 07:52
浏览 134

如何在PHP中构建带有多个参数的WHERE子句[重复]

I have a HTML form which contains 4 fields . The user can query on one field or multiple fields.

Based on what fields the user selects I need to build a WHERE condition.

I can check if each one of the parameters has a value or not. But I am stuck with trying to build a WHERE clause dynamically based on whether the parameters are populated or not.

SELECT field1, field2,field3 
FROM table1 
WHERE field1 = param1 AND field2 = param2 
AND field3 = param3 AND field4 = param4

This is what I am doing for checking for one parameter:

if(isset($_POST)['param1'])) {
$param1 = mysqli_real_escape_string($mysqli, $_POST['param1']);
$stmt   = mysqli->prepare("SELECT field1, field2,field3
                            FROM table1 WHERE field1 = ?");
$stmt->bind_param("s", $param1);
$stmt->execute();
$num_of_rows = $stmt->num_rows;

Based on the above code I need to check the parameters and then build a WHERE clause dynamically.

I hope the question is clear . If not please let me know. Also please note my code is taking care to prevent SQL injection. I basically need the logic to build the WHERE clause.

</div>
  • 写回答

3条回答 默认 最新

  • dongwei9365 2019-08-12 07:55
    关注

    You can do it with simple boolean logic

    WHERE (param1 is null or field1 = param1)
      AND (param2 is null or field2 = param2)
      AND (param3 is null or field3 = param3)
      AND (param4 is null or field4 = param4)
    

    If your parameters are empty strings instead of null then use

    WHERE (param1 = '' or field1 = param1)
    ...
    
    评论

报告相同问题?

悬赏问题

  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私