Сохраните все условия, которые пользователь хочет выполнить, и array
и implode
их в строку для вашего запроса:
$conditions = array();
if (isset($_POST['plantType']) && is_string($_POST['plantType']))
$conditions[] = "PlantType = '".mysql_real_escape_string($_POST['plantType'])."'";
if (isset($_POST['englishName']) && is_string($_POST['englishName']))
$conditions[] = "EnglishName = '".mysql_real_escape_string($_POST['englishName'])."'";
// repeat for color, soilType, ...
$query = "SELECT * FROM Plants";
if (count($conditions) > 0)
$query .= " WHERE ".implode(" AND ", $conditions);
$data = mysql_query($query);
Более короткая версия, которая делает то же самое:
$conditions = array();
$validColumns = array(
// Name of the column in DB => name of the parameter in URL
"PlantType" => "plantType",
"EnglishName" => "englishName",
"Color" => "color",
// add more here
);
// Loop through all valid columns the user might input.
foreach ($validColumns as $column => $param)
{
// If it is set and maybe if it is valid (add validation here).
// add this condition to our array
if (isset($_POST[$param]) && is_string($_POST[$param]) && !empty($_POST[$param]))
$conditions[] = "`$column` = '" .
// Don't forget to escape to prevent SQL-Injection.
mysql_real_escape_string($_POST[$param])."'";
}
$query = "SELECT * FROM Plants";
// Check if there are any conditions. Otherwise display all plants.
if (count($conditions) > 0)
$query .= " WHERE ".implode(" AND ", $conditions);
$data = mysql_query($query);