John Cart
John Cart

Reputation: 69

data not inserting in DB using array foreach function in PDO PHP

When I sending the data to the server in PHP with different input and same name I am not able to insert in my database through foreach function. I tried my best and all others functions available on stackoverflow but they all are not helpful for me.

Please help me how to make this fix and what will the real code to achieve my code functions. as developer console sending data is -

productID: 21202,33201,44202,44202,33204

Qty: 1,2,3,4,5

PHP

foreach($_POST['productID'] as $product) {
   foreach($_POST['Qty'] as $qty) {
      $stmt = $con->prepare("INSERT INTO `table` (product,qty) VALUES (:p,:q)");
      $stmt->execute(array(
       ':p' => $product,
       ':q' => $qty 
      ));
   }
}

echo $_POST['productID'];
response is = 21202,33204,332061

Upvotes: 0

Views: 128

Answers (1)

Nick
Nick

Reputation: 147166

It would appear your input data are comma separated strings of values, not arrays. To iterate over them, you need to convert them to an array using explode:

$stmt = $con->prepare("INSERT INTO `table` (product,qty) VALUES (:p,:q)");
foreach(explode(',', $_POST['productID']) as $product) {
   foreach(explode(',', $_POST['Qty']) as $qty) {
      $stmt->execute(array(
       ':p' => $product,
       ':q' => $qty 
      ));
   }
}

Note that you only need to prepare the statement once, so I've moved that outside the loop. You can also further optimise this code by binding parameters outside the loop:

$stmt = $con->prepare("INSERT INTO `table` (product,qty) VALUES (:p,:q)");
$stmt->bindParam(':p', $product);
$stmt->bindParam(':q', $qty);
foreach(explode(',', $_POST['productID']) as $product) {
   foreach(explode(',', $_POST['Qty']) as $qty) {
      $stmt->execute();
   }
}

Note that the above code will insert all combinations of productID and Qty values into the table (as does your original code), but you probably only want the matching values. In that case, use this code:

$stmt = $con->prepare("INSERT INTO `table` (product,qty) VALUES (:p,:q)");
$stmt->bindParam(':p', $product);
$stmt->bindParam(':q', $qty);
$quantities = explode(',', $_POST['Qty']);
foreach(explode(',', $_POST['productID']) as $key => $product) {
    $qty = $quantities[$key];
    $stmt->execute();
}

Upvotes: 2

Related Questions