我会尝试这样的事情:
$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 . ';'));