php - 试图从 $_SESSION foreach 循环 PHP 中获取索引
问题描述
我正在制作一个购物车,我正处于付款流程的最后。我遇到的问题是试图将购物车中的名称输入我的数据库。每次我这样做时,只有最后一个项目被输入,而不是整个项目,如果有超过 1 个。还想知道是否有一种方法可以根据项目的数量进入 SQL 行。例如我是什么试图实现。购物车里有苹果、橙子、香蕉
苹果->order1
橙色->order2
香蕉->order3
我得到了什么
苹果->不进去
橙色->不进去
香蕉->order1
PHP
if(isset($_SESSION['shopping_cart'])){
//keep track of how mnay products are in the shopping cart
$count = count($_SESSION['shopping_cart']);
//create sequantial array for matching array keys to products id's
$row_ids = array_column($_SESSION['shopping_cart'], 'id');
if (!in_array(filter_input(INPUT_GET, 'id'), $row_ids)){
$_SESSION['shopping_cart'][$count] = array
(
'id' => filter_input(INPUT_GET, 'id'),
'name' => filter_input(INPUT_POST, 'name'),
'price' => filter_input(INPUT_POST, 'price'),
'quantity' => filter_input(INPUT_POST, 'quantity')
);
}
else {echo="do nothing";}
}
}
}
if (isset($_POST['payment_process'])) {
foreach ($_SESSION['shopping_cart'] as $key => $product) {
echo "<div>".$product['name']."</div>";
}
}
$payment = "INSERT INTO `payment_info`
(order1,order2,order3)
VALUES
('".$product['name']."','".$product['name']."','".$product['name']."');";
mysqli_query($db,$payment);
解决方案
您的代码很复杂,而且您的数据库的结构方式,每个订单和/或付款限制为 3 件商品。
你应该有一个 invoice -> invoice_lines 的结构:
if(isset($_SESSION['shopping_cart']) && isset($_POST['payment_process'])){
//keep track of how many products are in the shopping cart if you need
$count = count($_SESSION['shopping_cart']);
$invoice = "INSERT INTO `invoices`
(date, customer)
VALUES
(time(), $_SESSION['customer']);";
mysqli_query($db,$invoice);
$new_invoice = mysqli_insert_id($db);
foreach ($_SESSION['shopping_cart'] as $key => $product) {
$invoice_line = "INSERT INTO `invoice_lines`
(invoice, id, quantity, price)
VALUES
($new_invoice, $product['id'], $product['quantity'], $product['price']);";
mysqli_query($db,$invoice_line);
}
}
else {
echo="do nothing";
}
显然,您将需要相应地重塑您的数据库结构并添加所需的代码来计算发票的总额。
推荐阅读
- spring - 混合参数策略 - 仅使用命名、位置或 JPA 序数策略之一
- c# - 在 c# 中获取属性的调用者信息
- javascript - 在 angular6 中刷新页面时,用户名将为空
- android-studio - Android Studio Web-view 访问存储的权限?
- python - 为什么图像块在提取时会像素化,但在连接时会变得正常?
- javascript - 我如何将所有这些代码存储在变量中
- python - 为 pip 设置私人仓库需要常规包的密码
- amazon-web-services - 尝试使用 Terraform 构建内部应用程序负载均衡器
- wordpress - 301 从不存在的子域重定向到子文件夹(关闭 wordpress 多站点)
- google-cloud-platform - Gsuite 应用程序 - 如何使用服务帐户?