试图从$ _SESSION foreach循环获取索引PHP

时间:2018-05-01 04:54:17

标签: php

我正在制作购物车,而且我正处于付款流程的最后阶段。我遇到的问题是尝试将购物车中的名称输入我的数据库。每次我这样做只输入最后一项而不是整个事情,如果有更多的1.还想知道是否有办法根据项目的数量进入SQL行。我是什么我试图实现。在购物车中有苹果,橙子,香蕉

apple - > order1

橙> order2

banana-> order3

我得到了什么

apple->不进入

orange->不进入

banana-> 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);

1 个答案:

答案 0 :(得分:3)

您的代码很复杂,而且数据库的结构方式也很复杂,每个订单和/或付款仅限于3件商品。

您应该有发票结构 - &gt; 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";
}

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