用于过滤PHP结果的下拉菜单从sql获取所有结果

时间:2015-09-24 14:59:34

标签: php mysql dropdown

我有这个下拉:

<select class="w-select filterdropdown" id="Tipo-de-cocina" name="tipofiltro" data-name="Tipo de cocina">
<?php
    if (isset($_GET['tipofiltro'])) {
        echo '<option value="' .$filtrocuisine.  '"> '  .$filtrocuisine. "</option>";

    } else {
        echo '<option value="Todos los tipos">Todos los tipos</option>';
    }

?>


              <option value="Japonesa">Japonesa</option>
              <option value="Mexicana">Mexicana</option>
              <option value="India">India</option>
              <option value="Mediterranea">Mediterranea</option>
              <option value="Italiana">Italiana</option>
              <option value="Americana">Americana</option>
              <option value="Asiatica">Asiatica</option>
              <option value="Thai">Thai</option>
              <option value="China">China</option>
              <option value="Francesa">Francesa</option>
              <option value="Turca">Turca</option>
              <option value="Latina">Latina</option>
              <option value="Africana">Africana</option>
              <option value="Griega">Griega</option>
              <option value="Arabe">Arabe</option>


            </select>

当用户选择字段“Todos los tipos”时,我怎么能做到这一点我的sql查询返回所有类型?这是背后的SQL:

if (isset($_GET['preciofiltro']) OR isset($_GET['preciofiltro'])) {
    $filtroprecio = $_GET['preciofiltro'];
    $filtrocuisine = $_GET['tipofiltro'];

    $sql = "SELECT Meals.Meal_ID, Meals.Name, Price, Cooks.Cook_ID 
            FROM Meals 
               INNER JOIN Cooks ON Cooks.Cook_ID = Meals.Cook_ID 
            WHERE Cooks.Area = '$area' 
              AND Meals.Capacity > 0 
              AND Meals.Price < '$filtroprecio' 
              AND Meals.Type = '$filtrocuisine'";

    $result = mysqli_query($conn, $sql);

基本上我需要诸如“AND Meals.Type = any”

之类的东西

干杯!

1 个答案:

答案 0 :(得分:1)

嗯,有更简单的方法,但没有重写所有内容,简单的答案是,如果用户从下拉列表中选择Todos los tipos,您实际想要做的是从查询中完全删除此选择条件AND Meals.Type = '$filtrocuisine',即您不再使用该条件限制查询。

所以改变你的脚本: -

我当然假设您已经从$_GET数组中获取数据,验证了它,并在我们开始使用此代码之前对其进行了清理。

if (isset($_GET['preciofiltro']) OR isset($_GET['preciofiltro'])) {
    $filtroprecio = $_GET['preciofiltro'];
    $filtrocuisine = $_GET['tipofiltro'];

$sql = "SELECT Meals.Meal_ID, Meals.Name, Price, Cooks.Cook_ID 
        FROM Meals 
           INNER JOIN Cooks ON Cooks.Cook_ID = Meals.Cook_ID 
        WHERE Cooks.Area = '$area' 
          AND Meals.Capacity > 0 
          AND Meals.Price < '$filtroprecio'";

if ( isset($filtrocuisine) && $filtrocuisine == 'Todos los tipos' ) {
    $sql .= " AND Meals.Type = '$filtrocuisine'";
}

$result = mysqli_query($conn, $sql);