我正在编写一个查询,该查询使用来自搜索表单的输入,其中品牌、类型和价格是可选的输入字段:
SELECT * FROM `database` WHERE `brand` LIKE "%' . $brand . '%" AND `type` LIKE "%' . $type. '%" AND `price` LIKE "%' . $price . '%"
我想知道,如果其中一个字段中没有输入任何内容,是否有一种方法可以说"all"。例如,如果他们没有在价格字段中输入值,是否有方法告诉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注入攻击(理想情况下,您应该使用带有准备好的语句的PHP PDO数据库连接器来净化输入)。
通常使用前端语言,而不是SQL。
但事实上,price LIKE '%'
确实意味着所有(NULL除外)。所以你可能很好。
如果您组织了表单字段,您可以执行以下操作:
<?php
$fields = array(
// Form // SQL
'brand' => 'brand',
'type' => 'type',
'price' => 'price',
);
$sql = 'SELECT * FROM `database`';
$comb = ' WHERE ';
foreach($fields as $form => $sqlfield)
{
if (!isset($_POST[$form]))
continue;
if (empty($_POST[$form]))
continue;
// You can complicate your $fields structure and e.g. use an array
// with both sql field name and "acceptable regexp" to check input
// ...
// This uses the obsolete form for mysql_*
$sql .= $comb . $sqlfield . ' LIKE "%'
. mysql_real_escape_string($_POST[$form])
. '"';
/* To use PDO, you would do something like
$sql .= $comb . $sqlfield . 'LIKE ?';
$par[] = $_POST[$form];
*/
$comb = ' AND ';
}
// Other SQL to go here
$sql .= " ORDER BY brand;";
/* In PDO, after preparing query, you would bind parameters
- $par[0] is value for parameter 1 and so on.
foreach($par as $n => $value)
bindParam($n+1, '%'.$value.'%');
*/