0

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

2 Answers 2

1

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

I was on it @O.Jones
0

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

1 Comment

Thanks for the help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.