0

I have a dynamic HTML form with three fields (item, number, cost). Users can add as many rows as they need. Because of this, I have set the fields names as item[], number[], cost[] in order to loop through the post and insert the values in the DB.

I have verified that the values are posted correctly up correctly through vardump, and I have checked that the following loop is picking up the values (both key and value) through printr. (and also simply echoing $value1).

foreach ($_POST as $field => $value) {
         foreach($value as $field1 => $value1){   
                 echo $field . ':' . $value1 . '</br>' ;
          }
};

However, if I try insert passing the values to execute, nothing happens (no data is inserted and I get no error message).

if($_POST['submit']){

try {

            $pdo->beginTransaction();  
            $stmt = $pdo->prepare('INSERT INTO invoice (item, number, cost) VALUES (?,?,?);'); 
            foreach ($_POST as $item => $value) {
                foreach($value as $item1 => $value1){ 
                $stmt->execute($value1);
                }
            }
            $pdo->commit();
    } 
    catch (Exception $e){
    $pdo->rollback();
    throw $e;
    }
}

I know that $value1 holds the correct values, but they are not being inserted. Can anyone help?

I have tried:

https://phpdelusions.net/pdo_examples/insert#multiple
PDO insert statement with loop through $_POST array
PDO insert array values Insert multiple rows using form and PDO
Need php pdo implode arrays and insert multiple rows in mysql

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
Rob
  • 1
  • 2

1 Answers1

1

As your $_POST array contains columns you need to get values from the corresponding cells, i.e. for the first row you need items[0], number[0] and cell[0] and so on. So iterate over the first column, get the index and use that index for the other two

        foreach ($_POST['item'] as $i => $item) {
            $stmt->execute([$item, $_POST['number'][$i], $_POST['cost'][$i]]);
        }
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345