Mysql多选择器

时间:2016-09-04 14:14:46

标签: php mysql

我无法找到如何将这些多个选择器合并为一个。有什么帮助吗?

我已经尝试了clausule UNIT但是它不起作用。它用于HTML(+ php)形式的过滤目的:

<input type="text" name="town_from">

作为文本值的输入。它们分开工作但不能同时工作。

$sql_1 = "SELECT * FROM ship_db WHERE town_from = '$town_from' AND town_to = '$town_to' ORDER BY  top DESC, date_time_of_insert DESC";

$sql_2 = "SELECT * FROM ship_db WHERE price BETWEEN '$price_from' AND '$price_to' ORDER BY top DESC, date_time_of_insert DESC";

2 个答案:

答案 0 :(得分:0)

这是你想要的吗?

SELECT s.*
FROM ship_db s
WHERE (s.town_from = '$town_from' AND s.town_to = '$town_to') OR
      (s.price BETWEEN '$price_from' AND '$price_to')
ORDER BY s.top DESC, s.date_time_of_insert DESC;

注意:

  • 我假设你想要符合任一标准的行(因此OR)。如果您想要两者,请使用AND
  • 您应该使用参数化查询。也就是说,不要将用户输入直接放入查询中。
  • 据推测,price是一个数字。您应该将数字与数字进行比较并省去单引号(当然,这也可以通过使用参数来修复)。

答案 1 :(得分:0)

你能不结合where子句吗?

"SELECT * FROM ship_db 
  WHERE town_from = '$town_from' AND town_to = '$town_to'
  AND price BETWEEN '$price_from' AND '$price_to' 
  ORDER BY  top DESC, date_time_of_insert DESC";

或者您可以尝试动态构建它,例如:

$sql  = "SELECT * FROM ship_db ";
if(isset($town_from) && isset($town_from)){
  $where = "WHERE town_from = '$town_from' AND town_to = '$town_to'";
}
if(isset($price_from) && isset($price_to)){
  if(isset($where)){
    $where += " AND price BETWEEN '$price_from' AND '$price_to'";
  }else{
    $where = "WHERE price BETWEEN '$price_from' AND '$price_to'";
  }

}

$sql += $where;
$sql += " ORDER BY  top DESC, date_time_of_insert DESC";