简体   繁体   中英

How to insert combined array into mysql table using PDO statements

I have a combined array of the type [key] => value and want to insert it into mysql table using PDO prepared statement. My code is as shown below:

$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

You are just sending the value of the array to the execute function. Send the key and the value in an array:

$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;
}

Without combining arrays:

$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++;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM