简体   繁体   中英

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?

在此处输入图像描述

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM