基于此问题How to insert array into mysql using PDO and bindParam?
我正在尝试通过PDO将数组的值插入到mysql中。
我很难过,因为我不断收到以下错误。
SQLSTATE [HY093]:参数号无效:绑定变量数与令牌数不匹配
这一行$stmt->execute();
我猜这个问题与这一行有关
$stmt->bindParam(':val$count', $val,PDO::PARAM_STR);
特别是'val $ count',但我不确定到底出了什么问题。
问题:我做错了什么?我该如何解决这个问题?
无论如何,这里是我正在使用的代码和示例数组。
$lastInsertValue=87;
$qid[0][0]=1;
$qid[0][1]=1;
$qid[1][0]=2;
$qid[1][1]="null";
$qid[2][0]=3;
$qid[2][1]=0;
$array_count = count($qid);
if (isset($lastInsertValue))
{
try
{
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
$stqid=array();
$a=0;
for ($i=0; $i<$array_count; $i++)
{
$stqid[$a]=$lastInsertValue;
$a++;
$stqid[$a]=$qid[$i][0];
$a++;
$stqid[$a]=$qid[$i][1];
$a++;
}
$sql = "INSERT INTO qresults (instance, qid, result) VALUES ( :val0, :val1, :val2)";
$count = 0;
$stmt = $dbh->prepare($sql);
foreach ($stqid as $val)
{
$stmt->bindParam(':val$count', $val,PDO::PARAM_STR);
$count++;
}
$stmt->execute();
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
答案 0 :(得分:2)
哎呀,这么多问题。
您的阵列构建非常详细。试试这个
$stqid = array();
foreach ($qid as $qidArr) {
$stqid[] = $lastInsertValue; // no idea why you repeat this
$stqid[] = $qidArr[0];
$stqid[] = $qidArr[1];
}
如果您只是依赖于参数数量
,请使用位置占位符$sql = 'INSERT INTO ... VALUES (?, ?, ?)';
bindParam
使用您在每次循环迭代时覆盖的引用。您可能希望使用bindValue()
代替
您的查询只有3个占位符,但您的$stqid
数组有9个项目。这是您的错误来源。
答案 1 :(得分:2)
你在变量周围有单引号,它将被视为变量名$count
(不是值),尝试将变量连接到字符串。试一试:
$stmt->bindParam(':val' . $count, $val,PDO::PARAM_STR);
答案 2 :(得分:1)
for ($i=0; $i<$array_count; $i++)
{
$stqid[$a]=$lastInsertValue;
$a++;
$stqid[$a]=$qid[$i][0];
$a++;
$stqid[$a]=$qid[$i][1];
$a++;
}
所以在$i = 2
的情况下,它会添加$stqid[6]
,$stqid[7]
,$stqid[8]
所以
foreach ($stqid as $val)
{
$stmt->bindParam(':val$count', $val,PDO::PARAM_STR);
$count++;
}
会将:val0
提供给:val8
在您的查询中,您只有:val0
到:val2
。
在数据库中的一个字段中也有多个值是不好的。不要这样做。尝试以不同方式重新设计您的数据库
编辑:早上数学不好......对不起