我正在尝试用PHP创建一个购物篮,我想通过一堆IDS并为它们查询数据库。目前我收到了这个错误:
错误:SQLSTATE [42000]:语法错误或访问冲突:1064 SQL语法中有错误;检查与MySQL服务器版本对应的手册,以便在第1行''(1 \',\'10 \',\'6 \',\'23)''附近使用正确的语法
这是我正在使用的功能
function find_item_db($product_code) {
try{
$query = substr($product_code, 0,-1);
$product_codes = explode(",", $query);
$ids = '';
foreach($product_codes as $code) {
$params[] = $code;
$ids .= '?, ';
}
$ids = '(' . rtrim($ids, ', ') . ')';
//we need to get product name and price from database.
$sql = "SELECT * FROM `Sweets` WHERE `Sweet_ID` IN $ids";
$statement = $this->connection->prepare($sql);
$statement->execute($params);
return $result = $statement->fetchAll();
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage(). "<br/>";
}
}
有人能看到我在这里收到语法错误吗?
答案 0 :(得分:2)
您需要让每个值都有自己的占位符。尝试:
$product_codes = explode(",", $query);
$ids = '';
foreach($product_codes as $code) {
$params[] = $code;
$ids .= '?, ';
}
$ids = '(' . rtrim($ids, ', ') . ')';
//we need to get product name and price from database.
$sql = "SELECT * FROM `Sweets` WHERE `Sweet_ID` IN $ids";
$statement = $this->connection->prepare($sql);
$statement->execute($params);
注意$ids
只是一个占位符列表,实际值绑定在execute
。
它是如何工作的粗略演示:https://eval.in/520334