0

I'm making an application for a restaurant(With php and pdo). I need to insert orders. I loop through some products that you can order with an input field so you can select how many of those products you want to order. But i don't know how to insert this in multiple records. so for example. i want to order 1 cola and 1 pepsi. it needs to create 2 records.

I tried to post the data but nothing happened

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">

So i fill in the number of products i want to order but nothing happens when i submit it

picture of form

Strawberry
  • 33,750
  • 13
  • 40
  • 57
HelpMePLS
  • 19
  • 2
  • So you have a form but you're adding multiple fields to it with the same name. In your PHP script the `$_POST` variable will of course not understand that it has to store 2 values into 1 variable. – Dirk Scholten May 20 '19 at 08:12
  • @DirkScholten I'm looping through multiple products so how can i add unique names to them? – HelpMePLS May 20 '19 at 08:20
  • Note that `LEFT JOIN x... WHERE x=` is the same as `INNER JOIN x` – Strawberry May 20 '19 at 09:01

1 Answers1

0

You could make an array of "gerecht aantallen" .

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

This way you will get an array in $_POST['GerechtID'] that you can loop through. For example:

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

To insert multiple values at once using PDO check out: PDO Prepared Inserts multiple rows in single query

Bart Bergmans
  • 4,061
  • 3
  • 28
  • 56