这最终对我有用。它是一个小项目,因此效率不是什么大问题。只是想知道它现在的样子。
我尝试按照建议的方式进行操作,但我并没有真正理解它,因此当我无法正常工作时,我无法解决问题:P。
我明白了。
if(!empty($_POST))
{
$project = $_POST['project'];
if ($project == "All") {
$project = '';
}
$category = $_POST['category'];
if ($category == "All") {
$category = '';
}
$services = $_POST['services'];
if ($services == "All") {
$services = '';
}
$priority = $_POST['priority'];
if ($priority == "All") {
$priority = '';
}
$query = $db->prepare
("SELECT * FROM event
WHERE Project LIKE '%$project%' AND
EventCategory LIKE '%$category%' AND
EventServices LIKE '%$services%' AND
EventPriority LIKE '%$priority%';");
$query->execute();
$result = $query;
$db= NULL;
}
答案 0 :(得分:1)
一种可能性是根据您拥有的值构建查询。在此代码中,我根据post值为查询添加条件。过滤器值本身放在一个数组中以用作查询的参数,因为这样可以消除SQL注入的风险而不会有太多麻烦。
结果如下:
$extraConditions = '';
$params = array();
if ($project !== 'ALL') {
$extraConditions .= ' AND project = :project';
$params[':project'] = $project;
}
if ($priority !== 'ALL') {
$extraConditions .= ' AND priority = :priority';
$params[':priority'] = $priority;
}
if ($category !== 'ALL') {
$extraConditions .= ' AND category = :category';
$params[':category'] = $category;
}
$query = $db->prepare
("SELECT * FROM event WHERE 1 = 1 $extraConditions");
$query->execute($params); // <- This is where you pass the filter values.
由于懒惰而添加了1=1
。每个额外条件前面都有AND
。如果查询中已经没有WHERE 1=1
,则它将无效,您必须将第一个AND更改为WHERE
。我认为这更清洁了。
您可以稍微更改一下以定义过滤器列表。如果它们与列名匹配,那么您可以创建一个简单的循环,并且只需将它们添加到filters
数组就可以允许对额外列进行过滤。
$extraConditions = '';
$params = array();
$filters = array('project', 'category', 'priority');
foreach ($filters as $filter)
{
if (array_key_exists($filter, $_POST)
{
$value = $_POST[$filter];
$extraConditions .= " AND $filter = :$filter";
$params[":$filter"] = $value;
}
}
$query = $db->prepare
("SELECT * FROM event WHERE 1 = 1 $extraConditions");
$query->execute($params);
这两种解决方案都使用查询参数,因此它比将帖子值直接放入查询中更安全。
答案 1 :(得分:-1)
在sql wheris中没有WHERE条件的通配符,除了LIKE用于文本字段,对于你的任务,你需要构建你的查询取决于条件
答案 2 :(得分:-1)
您可以使用LIKE运算符
SELECT * FROM event
WHERE Project = '$project' AND --where your project variable can have the value '%' instead of All
EventCategory = '$category' AND
EventServices = '$services' AND
EventPriority = '$priority';