我正在努力修改以下(有效)以使用预先准备好的声明:
echo "<div class=\"debug\">
<h4>values \$_POSTed from *LINE-ITEMS TABLE* in input.php:</h4>
<table>";
foreach ($_POST['date'] as $i => $value) {
$invNum = $_POST['invNum'];
$date = $_POST['date'][$i];
$hours = $_POST['hours'][$i];
$rate = $_POST['rate'][$i];
$dateTotal = $_POST['dateTotal'][$i];
echo "<tr>
<td>".$i."</td>
<td>".$date."</td>
<td>".$hours."</td>
<td>".$rate."</td>
<td>".$dateTotal."</td>
</tr>";
$query = "INSERT INTO Invoice_Line_Items SET
INVOICE_NUMBER = '$invNum',
DATE = '$date',
HOURS = '$hours',
RATE = '$rate',
DATE_TOTAL = '$dateTotal'
ON DUPLICATE KEY UPDATE
INVOICE_NUMBER = VALUES(INVOICE_NUMBER),
DATE = VALUES(DATE),
HOURS = VALUES(HOURS),
RATE = VALUES(RATE),
DATE_TOTAL = VALUES(DATE_TOTAL)
";
} // END foreach
echo "</table></div>";
我一直在尝试调整在此上面运行的(工作)预处理语句/查询在同一页面中,该页面将一行插入另一个表中。但是,第二个查询(进入不同的db表)从源表单中的行项表中插入多个(动态#)行的数据。
我一直在攻击它好几个小时,但我无法理清如何使用line-items循环实现预处理语句。我认为这将是沿着这些方向,但这不是插入。
echo "<div class=\"debug\">
<h4>values \$_POSTed from *LINE-ITEMS TABLE* in input.php:</h4>
<table>";
// this is the line-items table in the form; don't I have to get these values before the query?
foreach ($_POST['date'] as $i => $value) {
$invNum = $_POST['invNum'];
$date = $_POST['date'][$i];
$hours = $_POST['hours'][$i];
$rate = $_POST['rate'][$i];
$dateTotal = $_POST['dateTotal'][$i];
// confirm vars/values
echo "<tr><td>".$i."</td><td>".$date."</td><td>".$hours."</td><td>".$rate."</td><td>".$dateTotal."</td></tr>";
$stmt = $mysqli->stmt_init();
$query = "INSERT INTO Invoice_Line_Items
INVOICE_NUMBER = '$invNum',
DATE = '$date',
HOURS = '$hours',
RATE = '$rate',
DATE_TOTAL = '$dateTotal'
ON DUPLICATE KEY UPDATE
INVOICE_NUMBER = VALUES(INVOICE_NUMBER),
DATE = VALUES(DATE),
HOURS = VALUES(HOURS),
RATE = VALUES(RATE),
DATE_TOTAL = VALUES(DATE_TOTAL)
";
if ($stmt->prepare($query)) {
$stmt -> bind_param("ssddd", $invNum, $date, $hours, $rate, $dateTotal);
$stmt -> execute();
$stmt->close();
} // if $stmt
} // END foreach
echo "</table></div>";
有人可以说清楚吗?非常感谢。
SVS
答案 0 :(得分:1)
您不需要
$stmt = $mysqli->stmt_init();
您应该可以致电
$stmt = $mysqli->prepare($query);
另一个问题是你在>>你的循环中设置了查询。你不应该这样做。将$stmt
移到循环外部,只有在设置变量后才在execute
内运行。最后,您需要添加?
,以便MySQL知道参数
$query = "INSERT INTO Invoice_Line_Items
INVOICE_NUMBER = ?,
DATE = ?,
HOURS = ?,
RATE = ?,
DATE_TOTAL = ?
ON DUPLICATE KEY UPDATE
INVOICE_NUMBER = VALUES(INVOICE_NUMBER),
DATE = VALUES(DATE),
HOURS = VALUES(HOURS),
RATE = VALUES(RATE),
DATE_TOTAL = VALUES(DATE_TOTAL)
";
$invNum = $date = $hours = $rate = $dateTotal = '';
$stmt = $mysqli->prepare($query);
$stmt->bind_param("ssddd", $invNum, $date, $hours, $rate, $dateTotal);
foreach ($_POST['date'] as $i => $value) {
$invNum = $_POST['invNum'];
$date = $_POST['date'][$i];
$hours = $_POST['hours'][$i];
$rate = $_POST['rate'][$i];
$dateTotal = $_POST['dateTotal'][$i];
$stmt->execute();
}