从 php foreach 插入多行 [英] Inserting multiple rows from php foreach
问题描述
我有一个带有动态(用户确定)行数的 html 表单,每行都有多个输入;我正在尝试实现一个将插入行的 MySQL 查询进入数据库表,或多或少逐行(尽管该表外部有一个 $_POSTing 值,我也会将其添加到 INSERT 中).
I have an html form with dynamic (user-determined) number of rows, each with several inputs; I'm trying to achieve a MySQL query which will insert rows into the db table, more or less row-for-row (although there is a value $_POSTing from outside this table which I will also add to the INSERT).
我像这样检索这些值:
<?php
if (isset($_POST['submit'])) {
$lineItems = array();
foreach ($_POST['date'] as $i => $value) {
$customer = $_POST['customer'][$i]; // this value is from *outside* the line items table
$date = $_POST['date'][$i];
$time = $_POST['time'][$i];
$fee = $_POST['fee'][$i];
$lineItems[] = "('$customer', '$date', '$time', '$fee')";
// I realize the query should be outside the loop, but what I'm trying to do is something like this (pseudo-code):
$query = "INSERT INTO Line_Items (CUSTOMER, DATE, TIME, FEE) VALUES ". implode(", ", $lineItems)
. "ON DUPLICATE KEY UPDATE
CUSTOMER = VALUES(CUSTOMER),
DATE = VALUES(DATE),
TIME = VALUES(TIME),
FEE = VALUES(FEE)
";
}
}
?>
使用此查询 - 在循环内或循环外 - 我只插入来自最后一行输入的值;有人可以用一个例子解释一下如何构造查询以插入多个行项目和适当的查询?非常感谢.
With this query - inside or outside the loop - I'm only inserting values from the last row of inputs; can someone please explain with an example how to construct a query to insert multiple line items and the appropriate query? Thank you so much.
推荐答案
换行 $lineItems[] = "('$customer', '$date', '$time', '$fee')";
到 $lineItems[] = "(".$customer.",".$date.",".$time.",".$fee.")";
这篇关于从 php foreach 插入多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!