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

时间:2013-11-25 16:30:43

标签: php mysql

我正在我的网站上创建一个搜索功能,可以在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,但没用。

1 个答案:

答案 0 :(得分:0)

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

// 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");