【问题标题】:If variable is certain condition then don't run part of sql statement at all如果变量是特定条件,则根本不运行部分 sql 语句
【发布时间】:2022-01-10 16:07:39
【问题描述】:

我有以下 SQL 语句:

"SELECT * 
FROM products 
WHERE productage >= '$age' 
  AND productbrand='$brand'
  AND productinterest='$interest'
  AND (productprice >= '50' OR productprice='none')
  AND productexpdate >= CURDATE();"

如果 $age、$brand 或 $interest 是“全部”,我希望它们甚至不显示,在该变量下显示产品表中的所有内容。这是可能的吗,还是我需要根据 $age、$brand 或 $interest 的值创建多个 SQL 语句?

希望你能理解我的问题,如果不明白请告诉我!

【问题讨论】:

  • (可能)旁注:不要使用字符串插值或连接将值获取到 SQL 查询中。这很容易出错,并且可能使您的程序容易受到 SQL 注入攻击。使用参数化查询。见"How to include a PHP variable inside a MySQL statement""How can I prevent SQL injection in PHP?"
  • 只需检查 php 中的每个变量,如果该变量为 'all',则不要包含该部分代码。那么这只是一个字符串生成器问题。
  • varchar 的价格也是错误的。使用数字类型,如果没有价格,则使用NULL 作为值,而不是'none'

标签: php sql


【解决方案1】:

OR“全部”

... 
WHERE ('$age' = 'all' OR productage >='$age') 
  AND ('$brand'='all' OR productbrand='$brand') 
  AND ('$interest'='all' OR productinterest='$interest')
...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-20
    • 2021-07-04
    • 2018-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多