使用MySQL和PHP搜索多个值的最有效方法


Most efficient way of searching multiple values with MySQL and PHP

我在我的网站上做了一个搜索功能,可以在phpvms_schedules表中找到航班,使用HTML表单和一些不同的搜索参数:

<form method="get" action="">
    <select name="code" value="<?php echo $_GET['code'];?>" required>
        <?php
            // select all airlines
            $query = mysql_query("SELECT * FROM phpvms_airlines WHERE enabled=1");
            // loop thru
            while($row = mysql_fetch_assoc($query)) {
        ?>
        <option value="<?php echo $row['code'];?>"><?php echo $row['name'];?></option>
        <?php
            } // end loop
        ?>
    </select><br /><br />
    <input type="text" name="depicao" maxlength="5" placeholder="Airport of Departure" value="<?php echo $_GET['depicao'];?>"><br />
    <input type="text" name="arricao" maxlength="5" placeholder="Airport of Arrival" value="<?php echo $_GET['arricao'];?>"><br />
    <input type="text" name="mindis" maxlength="5" placeholder="Minimum distance" value="<?php echo $_GET['mindis'];?>"><br />
    <input type="text" name="maxdis" maxlength="5" placeholder="Maximum distance" value="<?php echo $_GET['maxdis'];?>"><br />
    <input type="submit" name="submit" value="Search">
</form>

考虑到其中一些参数不会由用户填写,用这些参数构造MySQL查询最有效的方法是什么?

我试过SELECT * FROM phpvms_schedules WHERE code='$code' OR depicao='$depicao' OR arricao='$arricao' OR distance >= $mindis AND distance <= $maxdis,但没有用。

这是我最终采用的解决方案:

// sanitise the user inputs
$code = strip_tags(mysql_real_escape_string($_GET['code']));
$depicao = strip_tags(mysql_real_escape_string($_GET['depicao']));
$arricao = strip_tags(mysql_real_escape_string($_GET['arricao']));
$mindis = strip_tags(mysql_real_escape_string($_GET['mindis']));
$maxdis = strip_tags(mysql_real_escape_string($_GET['maxdis']));
// start constructing the WHERE clause for the query
$WHERE = "enabled=1";
if(strlen($code)!=0) {
    $WHERE .= " AND code='$code'";
}
if(strlen($depicao)!=0) {
    $WHERE .= " AND depicao='$depicao'";
}
if(strlen($arricao)!=0) {
    $WHERE .= " AND arricao='$arricao'";
}
if(strlen($mindis)!=0) {
    $WHERE .= " AND distance >= $mindis";
}
if(strlen($maxdis)!=0) {
    $WHERE .= " AND distance <= $maxdis";
}
// query
$query = mysql_query("SELECT * FROM phpvms_schedules WHERE $WHERE");