-2

I am new to PDO and need to insert simple array data to a table. print_r($ID) and print_r($CODE) are as follows respectively,

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)
Array
(
    [0] => 1008M
    [1] => 1039E
    [2] => 1040E
    [3] => 198M
)

$ID and $CODE are fetched through another query which has in another host. I need to insert following array data to a table using PDO. Here is my try.

<?php

$db = new PDO("mysql:host=localhost;dbname=testdatabase", 'root', '');
$db ->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$sql = "INSERT INTO dummy (ID, CODE) VALUES (?,?)";
$stmt = $db->prepare($sql);
$stmt->execute(array($ID, $CODE));

?>

But this provides me an notice on,

Notice: Array to string conversion in C:\xampp\htdocs\mytestdata\test1.php on line 36

and the output in the dummy table shows as follows,

ID CODE
0  array

can someone show me where I have messed this code?

Expected Result:

ID CODE
1  1008M
2  1039E
3  1040E
4  198M
veganbu chat
  • 106
  • 11

1 Answers1

-1

I guess you need merge two array (ID,CODE), beacuse excute method can use one array. This is reason because your print is ID = 0, and CODE = array.

You can use array_combine to combine values of ID to key of CODE.

Update :

$ID = [
    "0" => 1,
    "1" => 2,
    "2" => 3,
    "3" => 4,
];

$CODE = [
    "0" => "1008M",
    "1" => "1039E",
    "2" => "1040E",
    "3" => "198M",
];

$result = array_combine($ID,$CODE);

$db = new PDO("mysql:host=localhost;dbname=stackoverflow", 'root', 'root');
$db ->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

foreach($result as $key => $value){
    $sql = "INSERT INTO dummy (ID, CODE) VALUES (?,?)";
    $stmt = $db->prepare($sql);
    $stmt->execute(array($key,$value));
}

I hope I was helpful. Best regards,

tecnico57
  • 37
  • 2