我有一个产品目录页面,通过ajax显示产品。 Ajax调用的代码如下:
function updateProducts(opts){
$.ajax({
type: "POST",
url: "func.php",
dataType : 'json',
cache: false,
data: {filterOpts: opts},
success: function(records){
$('#slider').html(makeProdiv(records));
}
});
}
和func.php的代码如下:
$pdo = new PDO('mysql:host=localhost;dbname=filter', 'root', '');
$select = 'SELECT id, pname, prate, pdesc';
$from = ' FROM product';
$where = ' WHERE TRUE';
$opts = isset($_POST['filterOpts'])? $_POST['filterOpts'] : array('');
if (in_array("Shoes", $opts)) { $where .= " AND ptype = 'Shoes'"; }
if (in_array("Belt", $opts)) { $where .= " AND ptype = 'Belt'"; }
$sql = $select . $from . $where;
$statement = $pdo->prepare($sql);
$statement->execute();
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($results);
echo($json);
我面临的问题是:
当我在过滤器中同时选择“腰带”和“鞋子”时,没有显示任何结果,因为在选择这两个选项时查询结果如下:
SELECT id, pname, prate, pdesc FROM product WHERE TRUE AND ptype = 'Shoes'
AND ptype = 'Belt'
请告诉我如何实现这一点,因为单品检查工作正常。
答案 0 :(得分:3)
我想出来并实现如下:
$allptype = array('Belt','Shoes');
$selectedptype = array();
foreach($allptype as $ptype){
if(in_array($ptype,$opts)){
$selectedptype[] = $ptype;
}
}
if(count($selectedptype)){
$where .= " AND ptype IN ('".implode("', '", $selectedptype)."')";
}
对我来说似乎是好事。如果sombody有另一种方法,请随时发布。
答案 1 :(得分:0)
实际上,只要有两个冲突条件,您的查询就不会返回任何内容。 要解决此问题,您应该替换它:
$opts = isset($_POST['filterOpts'])? $_POST['filterOpts'] : array('');
if (in_array("Shoes", $opts)) { $where .= " AND ptype = 'Shoes'"; }
if (in_array("Belt", $opts)) { $where .= " AND ptype = 'Belt'"; }
通过(注意第一行末尾的变化):
$opts = isset($_POST['filterOpts'])? $_POST['filterOpts'] : array();
if(count($opts)){
$where .= " AND ptype IN (". str_pad('',count($opts)*2-1,'?,') .")";
}
这会产生一个像这样的WHERE子句:
AND ptype IN (?,?)
然后将 $ opts 值作为参数传递给执行。这对于SQL注入是安全的,因此您无需验证值是否在某些预定义列表中:
$statement->execute($opts);
这样,当您有其他可以选择的类型时,您无需调整代码。