使用前端搜索条件查询数据库


Using front end search criteria to query database

我正在创建一个搜索表单,允许客户端通过输入名字、姓氏、出生日期或其某些组合来搜索数据库中的用户。我遇到的问题是,我不确定如何处理创建查询的where子句,当任何字段都为空白时,更不用说如何绑定可能不存在的参数了。这是我的搜索框。

<form action="manageUsers.php"method="POST">
        <h3>Search Users</h3>
        <label for="lastName">Last Name:</label>
        <input type="text" name="lastName"><br>
        <label for="firstName">First Name:</label>
        <input type="text" name="firstName"><br>
        <label for="birthdate">Birthdate:</label>
        <input type="text" name="birthdate"><br>
        <input type="submit" value="Search Users">
</form>

我能想到的唯一一件事是使用一些if语句来动态创建基于字段是否为空白的查询。我肯定有人有一个我不知道或没有想到的简单解决办法。由于

我的方法是确保您的输入名称与MySQL数据库中的列匹配。它只是让映射更简单。然后您可以执行以下操作:

<?
    if(count($_POST)>0){
        // remove any key that has no value
        $data = array_filter($_POST);
        // define an array to hold the pieces of the where clause
        $where = array();
        // loop each of the variables and build the query
        foreach($data as $key => $value){
           // make things safe
           $key = mysql_real_escape_string($key);
           $value = mysql_real_escape_string($value);
           // push values to array
           array_push($where, "$key='$value'");             
        }
        // create teh select query by imploding the array of pieces
        $query = "SELECT * FROM tablename WHERE ".implode(" AND ", $where);
        // just to show sample output
        echo $query;
    }
?>
<form action=""method="POST">
        <h3>Search Users</h3>
        <label for="lastName">Last Name:</label>
        <input type="text" name="lastName"><br>
        <label for="firstName">First Name:</label>
        <input type="text" name="firstName"><br>
        <label for="birthdate">Birthdate:</label>
        <input type="text" name="birthdate"><br>
        <input type="submit" value="Search Users">
</form>

基本上它确保你张贴,然后做一个数组过滤器删除任何没有值的键(这样你就不会查询生日=")。然后循环遍历剩下的键并构建查询的那一部分。在循环之后,它将数组内爆并通过AND连接它,并将其与选择查询的其余部分一起抛出到字符串中。

输出类似于SELECT * FROM tablename WHERE lastName='efef' AND firstName='adsf'