[英]How to store my session array into my database
如何將 session 數組中的數據存儲到我的數據庫中? 輸入產品及其數量后,用戶將被引導至結帳頁面。 在結帳頁面中,填寫表格中的必要信息后,我嘗試使用按鈕將 session 數組提交到我的數據庫中。
我當前的代碼:
<?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;
}
}
但是,單擊按鈕后,我可以將客戶信息存儲到我的數據庫中,但我會收到 PHP 錯誤消息 Undefined index: name, Undefined index: quantity, Undefined index: price, Undefined index: pax?
您從$array
傳遞元素而不引用它們的indexes
,我的意思是沒有$array[0]
或$array[1]
。
您需要添加如下循環:
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;}
}
這將允許您保存來自shopping_cart
的每一行數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.