0

在我的数据库中,有一些具有不同类别和类型的车辆。我想创建一个表单来按类别和类型过滤车辆。所以表格代码如下。

<form action="" method="post">
Type <select name="search_type">
           <option value="jeep">Jeep</option>
           <option value="Wagon">Wagon</option>
           <option value="cab">Cab</option>
     </select>

Category <select name="search_category">
           <option value="Recondition">Recondition</option>
           <option value="Used">Used</option>
     </select>
    <input type="submit" name="search_submit"></form>

这是php代码:

if(isset($_POST['search_submit']))
{
  $all_vehicles    = FALSE;
  $search_type     = $_POST['search_type'];
  $search_category = $_POST['search_category'];
  $search_brand    = $_POST['search_brand'];

  $search_result   = mysql_query("SELECT * FROM vehicle_info WHERE type='$search_type' && catagory='$search_catagory' && brand='$search_brand' ORDER BY id desc");
}
else
{
  $search_result = mysql_query("SELECT * FROM vehicle_info ORDER BY id desc");
}

如果有人想搜索jeeps任何类别(使用过的或翻新过的),我应该在查询中写什么代码?

我知道我可以添加一个新<option>的“任何”。但我不知道如何在查询中使用它。

4

3 回答 3

1

您不必将其存储为任何内容。只需选择它而不选择类别。当然,假设这些是唯一存储的两个类别。

SELECT * FROM vehicle_info WHERE type = '$search_type' ORDER BY id DESC;

还; 请注意 SQL 注入。


在@dualed 处编辑以回应:

正确的。他可以简单地添加<option value="all">All categories</option>

并添加一个 if 语句:

if ($search_category != "all")
{
    $search_result = mysql_query("SELECT * FROM vehicle_info WHERE type = '$search_type' AND category = '$search_category' ORDER BY id DESC;");
}
于 2013-01-07T13:01:20.087 回答
0

你可以使用IN()

$search_result = mysql_query("SELECT * FROM vehicle_info WHERE type IN('used', 'recondition') AND ...

见:http ://dev.mysql.com/doc/refman/5.1/de/comparison-operators.html

于 2013-01-07T12:59:07.777 回答
0
 if(isset($_POST['search_submit']))
        {
            $all_vehicles=FALSE;
            $search_type = $_POST['search_type'];
            $search_category = $_POST['search_category'];
            $search_brand = $_POST['search_brand'];

            $query = "SELECT * FROM vehicle_info WHERE type='$search_type'";
            if(!empty($search_category)) {
               $query .= " && catagory='$search_catagory'";
            }
            if(!empty($search_brand)) {
                 $query .= " && brand='$search_brand'";
            }
            $query .= " ORDER BY id desc"


            $search_result = mysql_query($query);
        }
        else
        {
             $search_result = mysql_query("SELECT * FROM vehicle_info ORDER BY id desc");
        }
于 2013-01-07T13:02:51.390 回答