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

Php 使用前端搜索条件查询数据库,php,mysql,Php,Mysql,我正在创建一个搜索表单,允许客户端通过输入名字、姓氏、出生日期或其组合来搜索数据库中的用户。我遇到的问题是,当任何字段留空时,我不知道如何创建查询的where子句,更不知道如何绑定可能不存在的参数。这是我的搜索框 <form action="manageUsers.php"method="POST"> <h3>Search Users</h3> <label for="lastName">Last Name:<

我正在创建一个搜索表单,允许客户端通过输入名字、姓氏、出生日期或其组合来搜索数据库中的用户。我遇到的问题是,当任何字段留空时,我不知道如何创建查询的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>

可以安全地假设first name、last name和birthday都是数据库的独立列,并且输入名称与列名匹配吗?我将动态构建查询的WHERE子句。如果该字段为空,则将其保留在子句中。如果所有字段都为空,则省略查询的WHERE部分,因为它不是必需的。我还将过滤您的输入以防止SQL注入。