我正在编写一个查询,该搜索使用来自搜索表单的输入,其中Brand,Type和Price是可选输入字段:
SELECT * FROM `database` WHERE `brand` LIKE "%' . $brand . '%" AND `type` LIKE "%' . $type. '%" AND `price` LIKE "%' . $price . '%"
我想知道如果没有任何内容进入其中一个字段,是否有办法说'全部'。例如,如果他们没有在价格字段中输入值,有没有办法告诉SQL只是说忽略该部分,例如:
AND `price` LIKE "*";
所以reuslts仍按品牌和类型进行过滤,但可以有任何价格。
对此有任何建议表示赞赏!感谢
答案 0 :(得分:3)
正如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数据库连接器来清理输入。)
答案 1 :(得分:0)
通常你用前端语言,而不是SQL。
但price LIKE '%'
实际上意味着所有(除了NULL)。所以你可能没事。
答案 2 :(得分:0)
如果您的表单字段有条理,您可以执行以下操作:
<?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.'%');
*/