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
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?