我正在编写一个查询,该查询使用来自搜索表单的输入,其中品牌、类型和价格是可选输入字段:
SELECT * FROM `database` WHERE `brand` LIKE "%' . $brand . '%" AND `type` LIKE "%' . $type. '%" AND `price` LIKE "%' . $price . '%"
我想知道如果没有在其中一个字段中输入任何内容,是否有一种方法可以说“全部”。例如,如果他们没有在价格字段中输入值,是否有办法告诉 SQL 忽略该部分,例如:
AND `price` LIKE "*";
所以结果仍然按品牌和类型过滤,但可以有任何价格。
如有任何建议,我们将不胜感激!谢谢
最佳答案
正如 Ariel 所提到的,最好让 PHP 在您构建查询时进行过滤。这是以这种方式执行此操作的代码示例:
<?php
$sql = 'SELECT * FROM `database`';
$where = array();
if ($brand !== '') $where[] = '`brand` LIKE "%'.$brand.'%"';
if ($type !== '') $where[] = '`type` LIKE "%'.$type.'%"';
if ($price !== '') $where[] = '`price` LIKE "%'.$price.'%"';
if (count($where) > 0) {
$sql .= ' WHERE '.implode(' AND ', $where);
} else {
// Error out; must specify at least one!
}
// Run $sql
注意:请,请,请确保$brand
、$type
和$price
变量内容在您以这种方式使用它们之前会被清理,否则您容易受到 SQL 注入(inject)攻击(理想情况下,您应该使用 PHP PDO 数据库连接器和准备好的语句来清理输入)。
关于PHP SQL : Way to skip over section of a query if variable is blank,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12399950/