MySQL查询有多个WHERE,有些可能是空的

时间:2011-05-11 21:32:19

标签: php mysql sql database

我正在尝试创建一个用户可以输入的查询:名字,姓氏,昵称,成绩和性别。但是,其中一些字段可能为空。

我知道如何创建一个可以检查所有这些内容的查询。但是,如果没有给出它,我怎么能在它不会查询的地方。例如,用户可能希望按姓氏和性别进行搜索,而不是其他人。

我该怎么做呢?非常感谢你的帮助!

@Ibu,这是我到目前为止所做的:

// Now we need to query the database for these terms
$sql_query = "SELECT * FROM `students` WHERE `first_name` = '" . $first_name . "' AND `last_name` = '" . $last_name . "' AND `nick_name` = '" . $nick_name . "' AND `grade` = '" . $grade . "' AND `gender` = '" . $gender . "'";
$result = mysql_query($sql_query);

// Let's check to make sure there is an actual result
$num_rows = mysql_num_rows($result);

if($num_rows < 1) {
    echo 'No student was found using that criteria.';
}

if($num_rows >= 1) {
    echo '<p>' . $num_rows . ' result(s) found. Below are the results:</p>';
    echo '<br />';
}

while($row = mysql_fetch_array($result)) {
    echo '
        <table border="1" width="400">
        <tr>
            <td colspan="2" align="center">Student Profile - ' . $row['last_name'] . ', ' . $row['first_name'] . '</td>
        </tr>
        <tr>
            <td>First Name: </td>
            <td>' . $row['first_name'] . '</td>
        </tr>
        <tr>
            <td>Last Name: </td>
            <td>' . $row['last_name'] . '</td>
        </tr>
        <tr>
            <td>Nick Name: </td>
            <td>' . $row['nick_name'] . '</td>
        </tr>
        <tr>
            <td>Grade: </td>
            <td>' . $row['grade'] . '</td>
        </tr>
        <tr>
            <td>Gender: </td>
            <td>' . $row['gender'] . '</td>
        </tr>
        </table> <br /><br />';

}

5 个答案:

答案 0 :(得分:2)

Erland Sommarskog是这个问题的事实上的来源:
http://www.sommarskog.se/dyn-search-2005.html#conclusion

我会以这样的格式编写每个参数化的AND

...AND ((@Param IS NULL)  OR (@Param = your_column))

答案 1 :(得分:1)

您可能希望动态构建SQL查询。阅读Gail Shaw在Catch-all queries上的博客文章。

答案 2 :(得分:1)

我通常更喜欢通过动态构建WHERE子句来创建“干净”查询。 如果您正确清理了$_POST中的数据并将其复制到$data,并且$data中的键以其将用于过滤的字段命名:

$sql = "SELECT ..fields.. FROM ..table..";
$search_enabled_fields = array('firstname', 'lastname', 'email', /* ..etc.. */);
$conditions = array();
foreach ($search_enabled_fields as $field) {
  if (!empty($data[$field])) { // isset and not an empty string
    $value = $data[$field];
    // maybe you could sanitize $value here if you didn't before..
    $conditions[] = "$field = '$value'";
  }
}
if (count($conditions) > 0) {
  $sql .= " WHERE ". implode(' AND ', $conditions);
}
// now, execute your $sql query..

改进这种逻辑,您还可以轻松地为每个字段实现不同的过滤器类型(例如,开始,包含,类似于..),并为大多数类型的搜索构建优化查询。

答案 3 :(得分:0)

只需检查$_POST vars并在其上构建查询。

就像这样的例子(这很糟糕,因为它没有消毒$_POST注射,但它是一个好的开始):

$whereSet = false;
$where = '';
if(isset($_POST['name'])){
    $whereSet = true;
    $where .= "WHERE name = '{$_POST['name']}'\n";
}
if(isset($_POST['nick'])){
    if(!$whereSet){
        $where .= "WHERE ";
        $whereSet = true;
    }
    else {
        $where .= "AND ";
    }
    $where .= "nick = '{$_POST['nick']}'\n";
}
//...etc

然后只需将$where变量附加到查询的末尾

答案 4 :(得分:0)

$query = "select * from somewhere where 1 = 1";
if(isset($_POST['something'])){
  $query .= " and something = '{$_POST['something']}'";
}
if(isset($_POST['something_else'])){
  $query .= " and something_else = '{$_POST['something_else']}'";
}

等。但是有转义输入

1 = 1是为了避免检查我们是否需要添加“where”关键字