我正在为一家餐厅制作一个应用程序(使用 php 和 pdo)。我需要插入订单。我循环浏览了一些您可以通过输入字段订购的产品,这样您就可以选择要订购的产品数量。但我不知道如何将其插入多个记录中。例如。我想订购 1 瓶可乐和 1 瓶百事可乐。它需要创建2条记录。
我尝试发布数据,但什么也没发生
if (isset($_POST["addbestelling"])){
global $db;
$gerechtid = htmlspecialchars($_POST["GID"]);
$aantal = htmlspecialchars($_POST["aantalG"]);
$sql = "INSERT INTO bestelling(GerechtID, Aantal) VALUES (:gerechtid,:aantal)";
$stmt = $db->prepare($sql);
$data = array("gerechtid" => $gerechtid, "aantal" =>$aantal);
try {
$stmt->execute($data);
echo "<script>alert('Succesvol geplaatst!');</script>";
}
catch (PDOException $e) {
echo $e->getMessage();
}
}
$voorgerecht = "
SELECT g.*
, s.Subgerecht
FROM gerecht g
LEFT
JOIN subgerecht s
ON s.GerechtID = g.GerechtID
WHERE s.Subgerecht = 'Voorgerecht';
";
foreach($db->query($voorgerecht) as $vg){
<div class="name-price row">
<p class="pr10">Gerecht</p>
<p class="pr10">€Prijs</p>
<?php
<input type="number" class="form-control" name="aantalG" placeholder="Aantal">
<input type="hidden" name="GID" value="<?php echo $vg["GerechtID"];?>">
}
?>
<input type="submit" name="addbestelling" class="btn btn-dark" value="Voeg toe">
所以我填写了我想订购的产品数量,但提交时没有任何反应
最佳答案
你可以创建一个“gerecht aantallen”数组。
<input type="number" class="form-control" name="aantalG[<?php echo $vg["GerechtID"];?>]" placeholder="Aantal">
这样你就会得到$_POST['GerechtID']
中的一个数组您可以循环浏览。例如:
foreach($_POST['GerechtID'] as $gerechtId => $aantal) {
echo $gerechtId . ' x ' . $aantal; // save row here.
}
要使用 PDO 一次性插入多个值,请执行以下操作: PDO Prepared Inserts multiple rows in single query
关于php - 使用 1 个表单插入多个订单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56216542/