'Best way to make multiple update with PDO

I need to update my table with multiple request. With a form, i get some values that i will take for update my table.

  $products =  [
    'prodotto1' => [
      'referenza' => $_POST['referenza1'],
      'prezzo' => $_POST['prezzo1'],
    ],
    'prodotto2' => [
      'referenza' => $_POST['referenza2'],
      'prezzo' => $_POST['prezzo2'],
    ],
    'prodotto3' => [
      'referenza' => $_POST['referenza3'],
      'prezzo' => $_POST['prezzo3'],
    ]
  ];

I thought to do this with a foreach :

function updateProducts(array $params){
    $pdo = $GLOBALS["db"];
    $sql = "UPDATE product SET REFERENCE=:reference, PRICE=:price WHERE REFERENCE=:reference";
    $stmt= $pdo->prepare($sql);

    foreach ($params as $prodotto ){
        if ($prodotto['referenza'] && $prodotto['prezzo'] ){
            $stmt->bindParam(':reference', $prodotto['referenza'], PDO::PARAM_STR);
            $stmt->bindParam(':price', $prodotto['prezzo']);
            $stmt->execute();

        }
    }
}

But i'm not sure that is the best way to do this.

Can u suggest me some goods practice ?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source