首页 > 解决方案 > 将会话值和数组插入数据库

问题描述

我在网上商店的购物车编程中遇到了障碍。这是我的购物车的主要代码。它有一个登录会话和一个购物车会话。我的订单表和产品表之间存在多对多关系,我需要在其中插入产品 ID (vare_id)、产品名称 (varenavn) 和项目数量 (kvantum)。大部分代码是英文的,但有些部分是挪威语的。我非常感谢帮助,因为这一直是一个问题。如果需要,我也可以添加数据库,但我认为没有必要。提前致谢。

<?php
// Initialize the session
session_start();

// Check if the user is logged in, if not then redirect him to login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: Login/login.php");
exit;
}
$conn = mysqli_connect("localhost", "root", "root", "mydb");  
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST["add_to_cart"]))  
{  
  if(isset($_SESSION["shopping_cart"]))  
  {  
       $item_array_id = array_column($_SESSION["shopping_cart"], "vare_id");  
       if(!in_array($_GET["vare_id"], $item_array_id))  
       {  
            $count = count($_SESSION["shopping_cart"]);  
            $item_array = array(  
                 'vare_id'               =>     $_POST["vare_id"],  
                 'varenavn'               =>     $_POST["hidden_name"],  
                 'varepris'          =>     $_POST["hidden_price"],  
                 'kvantum'          =>     $_POST["kvantum"]  
            );  
            $_SESSION["shopping_cart"][$count] = $item_array;  
       }  
       else  
       {  
            echo '<script>alert("Item Already Added")</script>';  
            echo '<script>window.location="varer.php"</script>';  
       }  
  }  
  else  
  {  
       $item_array = array(  
            'vare_id'               =>     $_POST["vare_id"],  
            'varenavn'               =>     $_POST["hidden_name"],  
            'varepris'          =>     $_POST["hidden_price"],  
            'kvantum'          =>     $_POST["kvantum"]  
       );  
       $_SESSION["shopping_cart"][0] = $item_array;  
  }  
  }  
  if(isset($_GET["action"]))  
  {  
  if($_GET["action"] == "delete")  
  {  
       foreach($_SESSION["shopping_cart"] as $keys => $values)  
       {  
            if($values["vare_id"] == $_GET["vare_id"])  
            {  
                 unset($_SESSION["shopping_cart"][$keys]);  
                 echo '<script>alert("Item Removed")</script>';  
                 echo '<script>window.location="varer.php"</script>';  
            }  
       }  
  }  
 }  


 $last_id = $conn->insert_id;

 $INSERT = "INSERT Into bestilling_has_vare (bestilling_id vare_id, varenavn, kvantum) 
 values('$last_id', 
'$_POST["vare_id"]', '$_POST["hidden_name"]', '$_POST["kvantum"]')";
 if ($conn->query($INSERT) === TRUE) {
 echo "insert compleat";
 }

 $conn->close();
 ?>

标签: phphtmlmysqlarrayssession

解决方案


推荐阅读