如何使用PDO语句将组合数组插入mysql表

时间:2019-03-27 12:05:48

标签: php mysql pdo

我有一个[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

2 个答案:

答案 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++;
}