Skip to content
Advertisement

How to use JSON encoded array in PHP

Essentially I have the following PDO Script that does an insert statement on a table – the data is received using a POST.

Currently the query runs once and uses the values from the POST.

$pdo->beginTransaction();
    
    $stmt = $pdo->prepare('
    INSERT INTO table1
    (`codeVal`,`id`)
    VALUES (:code, :id) ' );
        $stmt->execute([
        'code' => $_POST['code'], 
        'id' => $_POST['id']
        ]);
        

    //commit the changes
    $pdo->commit();

I would like to change this by passing an array using POST like this:

[
  {
    “code": "PC12335432",
    “id": “1"
  },
{
    “code": “PC123456",
    “id": “4"
  }
]

In need the query to run for each value in the array. In the example the query should run 2 times.

How can this be done?

Advertisement

Answer

You must loop thru $_POST

$pdo->beginTransaction();
$stmt = $pdo->prepare('
    INSERT INTO table1
    (`codeVal`,`id`)
    VALUES (:code, :id) ');

$data = '[{"code": "PC12335432","id": "1"},{"code": "PC123456","id": "4"}]';
$items = json_decode($data, true);

foreach ($items as $item) {
    $stmt->execute([
        'code' => $item['code'],
        'id' => $item['id']
    ]);
}


//commit the changes
$pdo->commit();

replace $items with $_POST or with variable that holds this data. You can only set prepare statement only once so you dont need to do it N times. Its also much better performance when you have big inserts in game.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement