繁体   English   中英

mysqli 查询中的条件将特定行的条件从 column1 更改为 column2

[英]Condition in mysqli query to change where condition from column1 to column2 for perticular row

这段代码是例如我将在应用之前添加用于 SQL 注入的代码。

我的表:

Example : book_master
|id |name   |regular_price  |special_price
|1  |book1  |100            |80             
|2  |book2  |160            |0
|3  |book3  |200            |150    
|4  |book4  |300            |0
|5  |book5  |450            |320

现在我的过滤器适用于regular_price

$get_books_sql = "SELECT * FROM books_master";

Filter : 1
if(isset($_GET['from'])){
    $from = $_GET['from'];
    $get_books_sql .= " WHERE regular_price >= $from";
}

Filter : 2
if(isset($_GET['to'])){
    $to = $_GET['to'];
    $get_books_sql .= " WHERE regular_price <= $to";
}
$get_book_result = $conn->query($get_books_sql);

我想为 special_price 添加条件,例如 if special_price > 0 所以如果过滤器 1 和 2 不适用于特定行的常规价格,则过滤器 1 和 2 应应用于 special_price。

注意:我将在之后添加额外的过滤器,如类别、升序和降序

For example : If $_GET['from'] = 60 and $_GET['to'] = 160 so result should be like:
|id |name   |regular_price  |special_price
|1  |book1  |100            |80             
|2  |book2  |160            |0
|3  |book3  |200            |150    

我还在该列上添加 asc desc。 谢谢你。

如果您想同时搜索常规价格和特价,如果存在特价,您可以使用OR和两个检查作为操作数。 在检查特价的操作数中还要检查特价是否存在。

...
WHERE special_price > 0
      AND special_price BETWEEN ?
                                AND ?
       OR regular_price BETWEEN ?
                                AND ?
...

如果您希望忽略常规价格,当存在特殊价格时,扩展第二个操作数以检查特殊价格是否不存在。

...
WHERE special_price > 0
      AND special_price BETWEEN ?
                                AND ?
       OR special_price = 0
          AND regular_price BETWEEN ?
                                    AND ?
...

请注意,如果特价不存在,将special_price设置为NULL而不是0会更好地表达。 是的,你应该使用参数化查询-马上

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM