我正在尝试进行具有多个选择框的查询,用户可以从下拉菜单中选择一个或多个值,但只有当用户选择一个选择框时,如果用户尝试选择两个或更多选择,它才能正常工作框值,它无法正确显示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);
答案 0 :(得分:1)
确保在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);
答案 1 :(得分:0)
$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
答案 2 :(得分:0)
我会尝试这样的事情:
$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 . ';'));