代码之家  ›  专栏  ›  技术社区  ›  AJFMEDIA

php mysql查询:多个下拉选项

  •  2
  • AJFMEDIA  · 技术社区  · 16 年前

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

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

    如果用户从所有3个下拉框中选择and选项,那么这种方法可以很好地工作。但是,如果用户仅选择一个位置(例如),如何使msql查询检查数据库。

    6 回复  |  直到 16 年前
        1
  •  1
  •   Aaron W.    16 年前
    $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之前,需要确保设置了搜索条件。

        2
  •  1
  •   d2burke    16 年前

    我一直碰到这个,这个设置不起作用。当只选择一个选项时失败。查询变成:

    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'":"";
    
        3
  •  1
  •   Toto    16 年前

    基于Aaron W.answer,这里有一个解决方案,在所有选项都为“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";
    
        4
  •  0
  •   Michael Madsen    16 年前

        5
  •  0
  •   cypher    16 年前
    $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 .

        6
  •  -1
  •   Tokk    16 年前
    $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 .= ';';