我正在使用下面的代码。代码工作,但我想,这样使用它来改变它bindparam如何使用PDO和bindParam将数组插入到mysql中?
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
$stqid=array();
for ($i=0; $i<$array_count; $i++){
$stqid[$i][0]=$lastInsertValue;
$stqid[$i][1]=$qid[$i][0];
$stqid[$i][2]=$qid[$i][1];
}
$values = array();
foreach ($stqid as $rowValues) {
foreach ($rowValues as $key => $rowValue) {
$rowValues[$key] = $rowValues[$key];
}
$values[] = "(" . implode(', ', $rowValues) . ")";
}
$count = $dbh->exec("INSERT INTO qresults(instance, qid, result) VALUES ".implode (', ', $values));
$dbh = null;
}
catch(PDOException $e){
echo $e->getMessage();
}
我更换了以下
$count = $dbh->exec("INSERT INTO qresults(instance, qid, result) VALUES ".implode (', ', $values));
与
$sql = "INSERT INTO qresults (instance, qid, result) VALUES (:an_array)";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(':an_array', implode(',', $values),PDO::PARAM_STR);
$stmt->execute();
但是插入不工作了(尽管我没有收到任何错误信息)。
问题:我做错了什么?我怎样才能重写代码来使用bindParam?
谢谢你更新你的答案。现在理解起来要容易得多:) – TryHarder 2012-03-25 06:12:52
当插入值的数量每次都不相同时,有没有办法做到这一点? – TryHarder 2012-03-25 08:14:06
是的,你只需根据你的需要生成你的查询字符串,并绑定与你生成的查询匹配的参数 – grifos 2012-03-26 18:30:25