你能看到这个查询有什么问题吗?我一直在看它很长时间,我看不到它。
错误: 您的SQL语法有错误;
查看与MySQL服务器版本对应的手册 在第1行的'''附近使用正确的语法
$sql="SELECT country_name FROM countries WHERE country_id IN (";
foreach($cartContentVsDatabase as $key => $val){
$sql.= $key['country_id'].",";
}
")";
答案 0 :(得分:2)
一些问题:
以下是您可以使用的代码:
// first put the countries in an array
foreach($cartContentVsDatabase as $key => $val){
$countries[] = $val['country_id'];
}
// create a list of `?`: one for every country
$in = join(',', array_fill(0, count($countries), '?'));
// use that in the query
$sql="SELECT country_name FROM countries WHERE country_id IN ($in)";
// Prepare the statement (this is PDO syntax)
$statement = $pdo->prepare($select);
// Pass the countries as parameter values, and execute
$statement->execute($countries);
有关此in (...)
子句上下文中有关预准备语句的更多信息,请参阅this Q&A。
答案 1 :(得分:1)
试试这个,
将")";
更改为$sql.= ")";
$array_count = count($cartContentVsDatabase);
$temp_count = 0;
$sql="SELECT country_name FROM countries WHERE country_id IN (";
foreach($cartContentVsDatabase as $key => $val){
$temp_count++;
if($array_count < $temp_count)
{
$sql.= $val['country_id'];
}
else
{
$sql.= $val['country_id'].",";
}
}
$sql.= ")";
答案 2 :(得分:0)
你可以通过
让生活变得更轻松$sql= "SELECT country_name FROM countries WHERE country_id IN (".implode(",",array_column($cartContentVsDatabase,"country_id")). ")";
您可以(也可能应该)使用准备好的查询,例如如下所示:
$sql= "SELECT country_name FROM countries WHERE country_id IN (".implode(",",array_fill(0,count($cartContentVsDatabase),"?")). ")";
然后在执行时绑定$cartContentVsDatabase
的内容。
答案 3 :(得分:0)
在您的代码中,您最终未正确连接")";
。您还可以将数据存储到数组中,而不是将implode()
用于逗号分隔值,例如:
示例:强>
<?php
$sql = "SELECT country_name FROM countries ";
$countries = array();
foreach($cartContentVsDatabase as $key => $val){
$countries[] = $val['country_id']; // store country id in your array
}
if(count($countries) > 0){
$countrylist = implode("','",$countries); // implode all country list with comma.
$sql .= "WHERE country_id IN ('$countrylist')";
}
echo $sql; // print your query.
?>
我仍然不知道,$key['country_id']
是否正确,我认为这应该是$val['country_id']
。