i have catalog page on products getting displayed via ajax. code ajax call below:
function updateproducts(opts){
$.ajax({ type: "post", url: "func.php", datatype : 'json', cache: false, data: {filteropts: opts}, success: function(records){ $('#slider').html(makeprodiv(records)); } });
}
and func.php has code below:
$pdo = new pdo('mysql:host=localhost;dbname=filter', 'root', ''); $select = 'select id, pname, prate, pdesc'; $from = ' product'; $where = ' true'; $opts = isset($_post['filteropts'])? $_post['filteropts'] : array(''); if (in_array("shoes", $opts)) { $where .= " , ptype = 'shoes'"; } if (in_array("belt", $opts)) { $where .= " , ptype = 'belt'"; } $sql = $select . $from . $where; $statement = $pdo->prepare($sql); $statement->execute(); $results = $statement->fetchall(pdo::fetch_assoc); $json = json_encode($results); echo($json);
the problem facing are:
when select both belt , shoes in filter no result getting displayed because query turns out below on selecting both options:
select id, pname, prate, pdesc product true , ptype = 'shoes' , ptype = 'belt'
please let me know how achieve single product check working fine.
indeed query return nothing have 2 conflicting conditions. resolve this, should replace this:
$opts = isset($_post['filteropts'])? $_post['filteropts'] : array(''); if (in_array("shoes", $opts)) { $where .= " , ptype = 'shoes'"; } if (in_array("belt", $opts)) { $where .= " , ptype = 'belt'"; }
by (notice change @ end of first line also):
$opts = isset($_post['filteropts'])? $_post['filteropts'] : array(); if(count($opts)){ $where .= " , ptype in (". str_pad('',count($opts)*2-1,'?,') .")"; }
this produces clause this:
and ptype in (?,?)
then pass $opts value argument execute. safe sql injection, don't need verify values in predefined list:
$statement->execute($opts);
this way don't need adapt code when have other types can selected.
Comments
Post a Comment