0

我正在尝试进行具有多个选择框的查询,用户可以从下拉菜单中选择一个或多个值,但它不起作用只有当用户尝试选择两个或多个选择框值时用户选择一个选择框才有效无法正确显示 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);
4

3 回答 3

1

AND确保在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);
于 2013-09-10T10:02:31.153 回答
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 . ';'));
于 2013-09-10T10:04:14.600 回答
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_stringhtmlspecialchars

于 2013-09-10T10:02:39.923 回答