未通过PDO循环插入多维数组值 [英] Multidimensional array values not inserted through PDO loop
问题描述
我有一个动态HTML表单,其中包含三个字段(项目,数字,费用).用户可以根据需要添加任意多的行.因此,我将字段名称设置为item [],number [],cost [],以便遍历帖子并将值插入DB.
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.
我已验证通过vardump正确正确地发布了值,并且我检查了以下循环是否正在通过打印机获取值(键和值). (并且还简单地回显$ value1).
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;
}
}
我知道$ value1拥有正确的值,但是没有插入它们.有人可以帮忙吗?
I know that $value1 holds the correct values, but they are not being inserted. Can anyone help?
我尝试过:
https://phpdelusions.net/pdo_examples/insert#multiple
通过$ _POST数组进行循环的PDO插入语句
PDO插入数组值 需要php pdo分解数组并在其中插入多行mysql
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
推荐答案
由于您的$ _POST数组包含列,因此您需要从相应的单元格中获取值,即,对于第一行,您需要项目[ 0],数字[0]和单元格[0],依此类推.因此,对第一列进行迭代,获取索引,并将该索引用于其他两列
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]]);
}
这篇关于未通过PDO循环插入多维数组值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!