保存所有條件,用戶想要滿足進入和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);
你應該爲用戶提供一些電臺和檢查搜索類型,examepl(PS做不是爲了得到安全的保護!):如果($ rado1)$ data = mysql_query($ querry1)elseif($ radio2)$ data = mysql_query($ querry2)elseif($ radio2)$ data = mysql_query($ querry3)...等等。 – nvcnvn 2012-03-14 17:06:08