Search MySQL Database with Multiple Fields in a Form

后端 未结 1 968
不思量自难忘°
不思量自难忘° 2020-12-14 05:25

I have created a form where the user can search the database, and the result depends on how the user fills out the form.
For example, say I have name, address, city, sta

相关标签:
1条回答
  • 2020-12-14 05:34

    Try this:

    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);
    
    0 讨论(0)
提交回复
热议问题