首页 > 解决方案 > 试图从 $_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);

标签: php

解决方案


您的代码很复杂,而且您的数据库的结构方式,每个订单和/或付款限制为 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";
}

显然,您将需要相应地重塑您的数据库结构并添加所需的代码来计算发票的总额。


推荐阅读