Combination of field search using PHP & MYSQL

后端 未结 3 840
长情又很酷
长情又很酷 2020-12-22 06:39

I am working on an assignment using PHP & MYSQL.

one of the tasks is to search on any combination of the fields. That includes Dropdown boxes populated from the

3条回答
  •  醉梦人生
    2020-12-22 06:57

    Instead of all those conditionals about whether to add AND when concatenating to the query, use an array and implode.

    $fields = array('sport' => 'sport',
                    'gender' => 'gender', 
                    'fname' => 'firstName',
                    'lname' => 'lastName',
                    'country' => 'country');
    $wheres = array();
    foreach ($fields as $postfield => $dbfield) {
        if ($_POST[$postfield] != 'showAll') {
            $wheres[] = "$dbfield = '" . mysql_real_escape_string($_POST[$postfield]) . "'";
        }
    }
    $selectString = "SELECT t2ath.lastName, t2ath.firstName, t2ath.image, t2ath.sport, t2ath.gender, t2ath.country, t2country.flag 
                     FROM t2ath LEFT JOIN t2country
                     ON t2ath.country = t2country.name";
    if (count($wheres) > 0) {
        $selectString .= " WHERE " . implode(" AND ", $wheres);
    }
    $result = mysql_query($selectString);
    

    To see how to do it similarly using PDO prepared statements, see my answer here: What code approach would let users apply three optional variables in PHP/MySQL?

提交回复
热议问题