使用表单中的多个字段搜索MySQL数据库

时间:2012-02-16 19:31:18

标签: php

我创建了一个用户可以搜索数据库的表单,结果取决于用户填写表单的方式。
例如,假设我有姓名,地址,城市,州和邮政编码字段,并且用户填写姓名和城市字段,结果反映了输入。当表单提交所有记录时都会显示。 对此,我写这个:

if(isset($_POST['submit'])) {
        $sql = mysql_query("SELECT * FROM table WHERE name LIKE '%" . $_POST['name'] . "%'
                   OR address LIKE '%" . $_POST['address'] . "%'
                   OR city LIKE '%" . $_POST['city'] . "%'
                   OR state LIKE '%" . $_POST['state'] . "%'
                   OR zip LIKE '%" . $_POST['zip'] . "%'");
    }


        <form method="post" action="<?php $_SERVER['PHP_SELF']; ?>">
            <tr>
                <td>Name:</td>
                <td><input type="text" name="name" /></td>
            </tr>
            <tr>
                <td>Address:</td>
                <td><input type="text" name="address" /></td>
            </tr>
            <tr>
                <td>City:</td>
                <td><input type="text" name="city" /></td>
            </tr>
            <tr>
                <td>State:</td>
                <td><input type="text" name="state" /></td>
            </tr>
            <tr>
                <td>Zip:</td>
                <td><input type="text" name="zip" /></td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td><input type="submit" name="submit" value="Search" /></td>
            </tr>
        </form>
    </table>

    <?php
        if(isset($_POST['submit'])) {
            while($row = mysql_fetch_array($sql)) {
                echo $row['name'] . "<br />";
            }
        }   
    ?>

但在这种情况下,用户可能会将字段留空。

1 个答案:

答案 0 :(得分:12)

试试这个:

if(isset($_POST['submit'])) {
    // define the list of fields
    $fields = array('name', 'address', 'city', 'state', 'zip');
    $conditions = array();

    // loop through the defined fields
    foreach($fields as $field){
        // if the field is set and not empty
        if(isset($_POST[$field]) && $_POST[$field] != '') {
            // create a new condition while escaping the value inputed by the user (SQL Injection)
            $conditions[] = "`$field` LIKE '%" . mysql_real_escape_string($_POST[$field]) . "%'";
        }
    }

    // builds the query
    $query = "SELECT * FROM TABLE ";
    // if there are conditions defined
    if(count($conditions) > 0) {
        // append the conditions
        $query .= "WHERE " . implode (' AND ', $conditions); // you can change to 'OR', but I suggest to apply the filters cumulative
    }

    $result = mysql_query($query);
相关问题