-1

So i'm creating a webshop project at the moment and i ran into a problem. I ask the user to add items in a shopping cart (which is a session array). After the user has decided what to buy, the user can place an order for those items. First the user will have to give some information to what address the user wants the package to be sent. This data is sent to the table 'orders' and this works fine, here i give the order an ID. Immediately after this I try to fill the orderdetails in with that same orderID:

The following code is resposible for reading out the data from the session array and then writing that same information in the table 'orderdetails'

$query2 = "INSERT INTO orderdetails (OrderID, productID, UnitPrice, Quantity) VALUES ($orderID, $productID, $UnitPrice, $Quantity)";

    if (!empty($_SESSION["shopping_cart"])) {       
        $orderID = mysqli_insert_id($conn);
        foreach ($_SESSION["shopping_cart"] as $keys => $values) {
            $productID = $values["item_productID"];
            $UnitPrice = $values["item_price"];
            $Quantity = $values["item_quantity"];
            mysqli_query($conn, $query2);
        }
        mysqli_close($conn);
    }
Mikhail Zhuikov
  • 1,213
  • 2
  • 9
  • 19

1 Answers1

0

Your query string is being set with the default null values of $orderID, $productID, etc. You have to remake that query each time. Put the entire query line inside your for loop.

...
$Quantity = $values["item_quantity"];
$query2 = "INSERT INTO orderdetails (OrderID, productID, UnitPrice, Quantity) VALUES ($orderID, $productID, $UnitPrice, $Quantity)";
mysqli_query($conn, $query2);
...

With that said, SQL Injection is a thing. Use prepared statements.

Liftoff
  • 24,717
  • 13
  • 66
  • 119
  • Thank you! This helped me out a lot! I included the prepared statements when the user adds items to the shoppingcart, tought that was enough. Now my program doesnt write the last item of the array tho.. Mhmm – KnowledgeRequest Dec 21 '20 at 07:50
  • 1
    You can never be too careful with SQL. I use prepared statements even when I have no parameters to bind at all. It's just a good habit to get into. – Liftoff Dec 21 '20 at 07:52