Multidimensional array values not inserted through PDO loop

隐身守侯 提交于 2020-03-21 10:24:55

问题


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


回答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]]);
        }


来源:https://stackoverflow.com/questions/56949773/multidimensional-array-values-not-inserted-through-pdo-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!