Skip to content
Advertisement

How to store my session array into my database

How do I store my data in session array into my database ? Upon entering the product and its quantity, the user will be directed to a checkout page. In the checkout page, upon filling up the necessary information in a form, I am trying to use a button to submit the session array into my database.

My current code:

<?php
    session_start();
    $array = $_SESSION['shopping_cart'];  
    $connect = mysqli_connect('localhost', 'root', '', 'table');
    ?>
    $sql = "INSERT INTO customer_order (productName, quantity, totalPrice, pax)";
    foreach($array as $product){
       $sql = "INSERT INTO p2_5.customer_order (productName, quantity, totalPrice, pax)";
       $sql .= " VALUES ('{$product['name']}', '{$product['quantity']}', '{$product['price']}', '{$product['pax']}')";
       if ($connect->query($sql)) {
          $errorMsg = "Connection failed: " . $connect->connect_error;
          $success = false;
   } 
}

However, upon clicking on the button, I am able to store client information into my database, but I would have an PHP error message Undefined index: name, Undefined index: quantity, Undefined index: price, Undefined index: pax ?

enter image description here

Advertisement

Answer

You’re passing elements from $array without referencing to their indexes, I mean without $array[0] or $array[1].

You need to add a loop like below:

foreach($array as $product){
   $sql = "INSERT INTO customer_order (productName, quantity, totalPrice, pax)";
   $sql .= " VALUES ('{$product['name']}', '{$product['quantity']}', '{$product['price']}', '{$product['pax']}')";
   if ($connect->query($sql)) {
       $errorMsg = "Connection failed: " . $connect->connect_error;
       $success = false;
   } 
   if ($errorMsg != "Connection failed: ") {echo $errorMsg; $connect->close(); return;}
}

This will allow you to save each row data from shopping_cart.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement