将“WHERE”子句条件放在一个数组中。我会这样做:
// filter out invalid values is important
$valid_class = array('a', 'b', 'c');
$valid_category = array('math', 'science', 'history');
// initialize array for WHERE clause conditions
$where = array('TRUE');
if (in_array($_POST['class'], $valid_class))
{
$where[] = 'class = "' . $_POST['class'] . '"';
}
if (in_array($_POST['category'], $valid_category))
{
$where[] = 'category = "' . $_POST['category'] . '"';
}
// use the array with the "implode" function to join its parts
$sql = 'SELECT * FROM table WHERE ' . implode(' AND ', $where);您可能希望使用比“TRUE”更有趣的东西来初始化$where数组(如果用户不按类别过滤类别,则会出现这种情况,因为我们不希望空的$ where数组到达最后一行)。例如:
$where = array();
$where[] = 'name = "' . mysql_real_escape_string($_POST['name']) . '"';