php mysql查询:多个下拉选项

时间:2010-09-17 11:40:28

标签: php mysql database

我有一个搜索框,用户可以选择一个$ type和$ rating的$ location。

$result = mysql_query("SELECT * FROM Places WHERE Location = '$location' and Type ='$type' and Rating = '$rating'")
or die(mysql_error()); 

如果用户从所有3个下拉框中选择并选项,则此工作正常 - 但是,如果用户仅选择某个位置,如何使msql查询检查数据库。

我想在所有3个下拉菜单上都有一个“任意”选项,因为他们希望将下拉列表留空。

由于

6 个答案:

答案 0 :(得分:1)

$searches = array();
if($location != 'any') $searches[] = "`Location` = '$location'";
if($type != 'any') $searches[] = "`Type` = '$type'";
if($rating != 'any') $searches[] = "`Rating` = '$rating'";
if(count($searches) > 0) {
    $result = mysql_query("SELECT * FROM Places WHERE " . implode(" AND ", $searches)) or die(mysql_error()); 
}

需要确保在运行SQL之前设置了搜索条件。

答案 1 :(得分:1)

我一直遇到这种情况,这种设置不起作用。仅选择一个选项时失败。查询变为:

SELECT * FROM Places WHERE AND 'Rating' = '$rating'

简单的解决方法是在查询开头的WHERE 1处,然后您可以添加 AND 'Rating' = '$rating'以任何方式你都觉得最方便。

$sql .= ($location)?" AND Location='$location'":"";
$sql .= ($type)?" AND Type='$type'"":"";
$sql .= ($rating)?" AND Rating='$rating'":"";

答案 2 :(得分:1)

基于Aaron W.回答,这是一个解决方案,当所有选项都是'any'时检索所有行:

$sql = "SELECT * FROM Places";
$searches = array();
if ($location != 'any') $searches[] = "`Location` = '$location'";
if ($type     != 'any') $searches[] = "`Type` = '$type'";
if ($rating   != 'any') $searches[] = "`Rating` = '$rating'";
if (count($searches) > 0) {
    $sql .= " WHERE " . implode(" AND ", $searches);
}
$sql .= ';';
echo "sql=$sql\n";

答案 3 :(得分:0)

动态构建查询,一次添加一个条件。如果选择“任何”,则不包括该部分条件。

答案 4 :(得分:0)

$result = mysql_query("
    SELECT * 
    FROM 
        Places 
    WHERE 
        (Location = '$location' OR '$location' = 'Any') 
    AND
        (Type ='$type' OR '$type' = 'Any')
    AND  
        (Rating = '$rating' OR '$rating' = 'Any')
")
or die(mysql_error());

此外,这是SQL INJECTION灾难。请使用转义功能,例如mysql_real_escape_string

答案 5 :(得分:-1)

$query = 'SELECT * FROM Places ';
if($location != "Any" || $type != "Any"|| $rating != "Any")
    $query .= 'WHERE ';
if($location != "Any")
   $query .= 'location = "'.mysql_real_escape_string($location).'" ';
if($type!= "Any")
   $query .= 'type= "'.mysql_real_escape_string($type).'" ';
if($rating!= "Any")
   $query .= 'rating= "'.mysql_real_escape_string($rating).'" ';
$query .= ';';