[英]Searching with multiple select boxes
我正在嘗試使查詢具有多個選擇框,用戶可以從下拉菜單中選擇一個或多個值,但是它不起作用,只有當用戶嘗試選擇兩個或多個選擇框值時,用戶選擇一個選擇框,它才起作用無法正確顯示where子句。 我在另一個網站上看到了此代碼,但無法正確選擇,如果有人可以幫助您理解或簡化...
if ($office != '') {
$where = ($where == '') ? 'WHERE ' : 'AND ';
$where .= "adpno = '$office'";
}
if ($sector!= '') {
$where = ($where == '') ? 'WHERE ' : 'AND ';
$where .= "sector= '$sector'";
}
if ($subsector!= '') {
$where = ($where == '') ? 'WHERE ' : 'AND ';
$where .= "subsector= '$subsector'";
}
mysql_query('SELECT * FROM sometable ' . $where);
確保在AND
和WHERE
之前和之后添加一個空格!
在您的代碼中,使用多個條件時,查詢可能構建為: SELECT * FROM sometable WHERE subsector=3AND sector=5
(請注意, AND
之前缺少空格)。
在您的代碼示例中,僅在AND/WHERE
之后有一個空格。 請注意,MySQL會忽略查詢中的空格,因此不必擔心它有時是否以雙倍空格結尾。 只要確保至少有一個空格,將查詢的所有元素分隔開即可。
編輯:另外,請確保每個if
連接到先前的WHERE
子句,而不是覆蓋它。 所以:
if ($office != '') {
$where .= ($where == '') ? ' WHERE ' : ' AND ';
$where .= "adpno = '$office'";
}
if ($sector!= '') {
$where .= ($where == '') ? ' WHERE ' : ' AND ';
$where .= "sector= '$sector'";
}
if ($subsector!= '') {
$where .= ($where == '') ? ' WHERE ' : ' AND ';
$where .= "subsector= '$subsector'";
}
mysql_query('SELECT * FROM sometable ' . $where);
$fields = array('sector' , 'subsector' , 'office');
$query = '';
foreach($fields as $field)
{
if($query != '')
$query .= ' AND ';
if( $input[$field] != '')
$query .= $field ." = '". $input[$field] ."'";
}
我建議您使用mysqli或pdo代替mysql。 $input
是進行“安全檢查”后的輸入值的數組,例如: mysql_escape_string
和htmlspecialchars
我會嘗試這樣的事情:
$conditions = '';
if ($tmp = @$_GET['office'])
$conditions .= ($conditions != '' ? ' AND ' : '') . 'office = \'' . mysql_escape_string($tmp) . '\'';
if ($tmp = @$_GET['sector'])
$conditions .= ($conditions != '' ? ' AND ' : '') . 'sector = \'' . mysql_escape_string($tmp) . '\'';
// ...
mysql_query('SELECT * FROM sometable' . ($conditions != '' ? ' WHERE ' . $conditions : '') . 'M');
如果您不僅擁有兩個或三個字段,那么foreach循環可能更適合:
$conditions = '';
$fields = array('office', 'sector', 'subsector', /*...*/);
foreach ($fields as $field)
if ($tmp = @$_GET[$field])
$conditions .= ($conditions != '' ? ' AND ' : '') . $field . ' = \'' . mysql_escape_string($tmp) . '\'';
mysql_query('SELECT * FROM sometable' . ($conditions != '' ? ' WHERE ' . $conditions : '') . 'M');
您甚至可以通過始終具有至少一個條件(未經測試,但應該可以工作)來稍微簡化代碼:
$conditions = 'TRUE';
$fields = array('office', 'sector', 'subsector', /*...*/);
foreach ($fields as $field)
if ($tmp = @$_GET[$field])
$conditions .= ' AND ' . $field . ' = \'' . mysql_escape_string($tmp) . '\'';
mysql_query('SELECT * FROM sometable WHERE ' . $conditions . ';'));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.