I am trying to use PDO to transcribe my code from mysqli.
I am making a simple low to high and vice-versa price filter
Inside preview.php I have a form with radio check buttons that are send to by POST
method into search.php file
What I tried in search.php where Validating occurs:
$sql = "SELECT * FROM products";
$cat_id = (($_POST['cat']!= '')?sanitize($_POST['cat']):'');
if($cat_id == ''){
$sql .= ' WHERE deleted = 0';
}else{
$sql .= "WHERE categories = '{$cat_id}' AND DELETED = 0";
}
$price_sort =(($_POST['price_sort'] != '')?sanitize($_POST['price_sort']):'');
$min_price =(($_POST['min_price'] != '')?sanitize($_POST['min_price']):'');
$max_price =(($_POST['max_price'] != '')?sanitize($_POST['max_price']):'');
if($min_price != ''){
$sql .= " AND price >= '{$min_price}'";
}
if($max_price != ''){
$sql .= " AND price <= '{$max_price}'";
}
if($price_sort == 'low'){
$sql .= " ORDER BY price";
}
if($price_sort == 'high'){
$sql .= "ORDER BY price DESC";
}
$sql->execute();
This is returning
Uncaught Error: Call to a member function execute() on a string
Error occurs where on execute
, I have tried using prepared statements and binding but I didn't find the solution
Thanks to @Chris and @Cobra_Fast I managed to resolve my full issue by doing:
- Making sure my PDO object is preparing the statement
- Binding all the parameters (escaping having variable inside query statement)
$sql = "SELECT * FROM products";
$cat_id = (($_POST['cat']!= '')?sanitize($_POST['cat']):'');
if($cat_id == ''){
$sql .= ' WHERE deleted = 0';
}else{
// $sql .= "WHERE categories = '{$cat_id}' AND DELETED = 0";
$sql .= "WHERE categories = :cat_id AND DELETED = 0";
}
$price_sort =(($_POST['price_sort'] != '')?sanitize($_POST['price_sort']):'');
$min_price =(($_POST['min_price'] != '')?sanitize($_POST['min_price']):'');
$max_price =(($_POST['max_price'] != '')?sanitize($_POST['max_price']):'');
if($min_price != ''){
$sql .= " AND price >= :min_price";
$sql->bindParam( ":max_price", $min_price, PDO::PARAM_STR );
}
if($max_price != ''){
$sql .= " AND price <= :max_price";
$sql->bindParam( ":max_price", $max_price, PDO::PARAM_STR );
}
if($price_sort == 'low'){
$sql .= " ORDER BY price";
}
if($price_sort == 'high'){
$sql .= " ORDER BY price DESC";
}
// $veza->query($sql);
$productQ =$veza->prepare($sql);
$productQ->bindParam( ":cat_id", $cat_id, PDO::PARAM_STR );
$productQ->execute();