我有一个[key] =>值类型的组合数组,并想使用PDO准备好的语句将其插入到mysql表中。我的代码如下所示:
$a = array('avocado', 'apple', 'banana');
$b = array('green', 'red', 'yellow');
$c = array_combine($a, $b);
print_r($c);
$stmt = $pdo->prepare("INSERT INTO fruits (name, color) VALUES (?,?)");
try {
$pdo->beginTransaction();
foreach ($c as $row)
{
$stmt->execute($row);
}
$pdo->commit();
}catch (Exception $e){
$pdo->rollback();
throw $e;
}
However, when I execute the statement, I get an error code:
Warning: PDOStatement::execute() expects parameter 1 to be array, string given in C:\xampp\htdocs\mysites\PDOmysql_tutorial\pdoInsert.php on line 19. Could I get a little help to correct my code or a comment if I am using the right approach. Thanks
答案 0 :(得分:1)
您只是将数组的值发送到execute函数。将键和值发送到数组中:
$a = array('avocado', 'apple', 'banana');
$b = array('green', 'red', 'yellow');
$c = array_combine($a, $b);
print_r($c);
$stmt = $pdo->prepare("INSERT INTO fruits (name, color) VALUES (?,?)");
try {
$pdo->beginTransaction();
foreach ($c as $name => $color)
{
$stmt->execute( [ $name, $color ] );
}
$pdo->commit();
}catch (Exception $e){
$pdo->rollback();
throw $e;
}
答案 1 :(得分:0)
不合并数组:
$a = array('avocado', 'apple', 'banana');
$b = array('green', 'red', 'yellow');
$stmt = $stmt->prepare("INSERT INTO fruits (name, color) VALUES (?,?)");
$fruit = "";
$color = "";
$stmt->bindParam(1, $fruit);
$stmt->bindParam(2, $color);
$count = count($a);
$x = 0;
while($count > $x){
$fruit = $a[$x];
$color = $b[$x];
$stmt->execute();
//echo $fruit . ": " . $color . "<br>";
$x++;
}