我正在尝试使用PDO从mysqli转录我的代码。
我正在制作一个简单的低到高,反之亦然价格过滤器
内部 preview.php 我有一个带有无线电检查按钮的表单,通过POST
方法发送到 search.php 文件
我在 search.php 中尝试了验证的地方:
$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();
这是返回
未捕获错误:在字符串
上调用成员函数execute()
在execute
上发生错误,我尝试过使用预处理语句和绑定,但我找不到解决方案
感谢@Chris和@Cobra_Fast,我设法解决了我的全部问题:
$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();
答案 0 :(得分:2)
string
是PHP中的原始类型,并且根本不公开任何方法,因此在execute()
上调用string
会使PHP感到困惑,因为您正在尝试像类实例一样使用它。
您似乎也在尝试执行SQL查询,这意味着您需要使用刚刚在$sql
中构建的SQL查询并使用数据库驱动程序执行它。
如果PDO看起来像这样:
$sql = "SELECT * FROM products";
// ...
$pdo->query($sql);