【问题标题】:Inserting multiple orders with 1 form使用 1 个表单插入多个订单
【发布时间】:2019-10-06 13:32:52
【问题描述】:

我正在为一家餐厅申请(使用 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">

所以我填写了我要订购的产品数量,但提交时没有任何反应

picture of form

【问题讨论】:

  • 所以您有一个表单,但您要向其中添加多个具有相同名称的字段。在您的 PHP 脚本中,$_POST 变量当然不会理解它必须将 2 个值存储到 1 个变量中。
  • @DirkScholten 我正在循环浏览多个产品,那么如何为它们添加唯一名称?
  • 注意LEFT JOIN x... WHERE x=INNER JOIN x是一样的

标签: php mysql sql pdo insert


【解决方案1】:

你可以创建一个“gerecht aantallen”数组。

&lt;input type="number" class="form-control" name="aantalG[&lt;?php echo $vg["GerechtID"];?&gt;]" placeholder="Aantal"&gt;

这样您将在$_POST['GerechtID'] 中获得一个可以循环遍历的数组。例如:

foreach($_POST['GerechtID'] as $gerechtId => $aantal) {
   echo $gerechtId . ' x ' . $aantal; // save row here.
}

要使用 PDO 检查一次插入多个值: PDO Prepared Inserts multiple rows in single query

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多