php - 将会话值和数组插入数据库
问题描述
我在网上商店的购物车编程中遇到了障碍。这是我的购物车的主要代码。它有一个登录会话和一个购物车会话。我的订单表和产品表之间存在多对多关系,我需要在其中插入产品 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();
?>
解决方案
推荐阅读
- android - 如何使用正则表达式为 EditText 设置输入掩码?
- c# - 有两个非常大的列表/集合 - 如何有效地检测和/或删除重复项
- android - React js 应用程序具有相同的文件夹图像,但在 ios png 图像中显示 alpha 透明度问题
- sql - 如果当前行中不可用,则从前一行获取日期值
- ios - 将值从 Objective-C 类传递给 Swift TableViewCell
- php - 找出数组中有多少个数大于 N
- ionic3 - 卡在复制完成,无法进行生产构建
- layout - 图表的自动布局
- python - 如何在 Django REST 框架中序列化继承的模型
- go - 由于某种原因,将值传递给通道正在阻塞线程