我对学习 MySQL 和 PhP 的工作原理仍然很陌生,我一直在尝试将作为 session 一部分的数组值放入 MySQL 数据库中,但我不知道如何操作或我做错了什么。我无法让查询从函数 checkouttodatabase() 中的数组中获取某些值。
我已经尝试遵循多个有关将 session 数组发布到 MySQL 数据库的教程和帖子,但无济于事。这似乎是“功能”,但不会将项目名称添加到数据库中,而是放入“Array”和值“0”
//将项目添加到数组
if (isset($_POST["add_to_cart"])) {
if (isset($_SESSION["shopping_cart"])) {
$item_array_id = array_column($_SESSION["shopping_cart"], "item_id");
if (!in_array($_GET["id"], $item_array_id)) {
$count = count($_SESSION["shopping_cart"]);
$item_array = array(
'item_id' => $_GET["id"],
'item_name' => $_POST["hidden_name"],
'item_price' => $_POST["hidden_price"],
'item_quantity' => $_POST["quantity"]
);
array_push($_SESSION['shopping_cart'], $item_array);
} else {
echo '<script>alert("Item Already Added")</script>';
echo '<script>window.location="shoppingcart.php"</script>';
}
} else {
$item_array = array(
'item_id' => $_GET["id"],
'item_name' => $_POST["hidden_name"],
'item_price' => $_POST["hidden_price"],
'item_quantity' => $_POST["quantity"]
);
$_SESSION["shopping_cart"][0] = $item_array;
}
}
//获取数组值并将其添加到数据库的函数
function checkouttodatabase() {
$connect = mysqli_connect("localhost", "root", "", "precisionmice");
mysqli_select_db($connect, 'precisionmice');
foreach($_SESSION['shopping_cart'] as $row => $id){
$sql="INSERT INTO orders (product, quantity, totalprice)
VALUES ('item_id','item_quantity','item_price')";
}
if(mysqli_query($connect, $sql)){
echo "Betaling bevestigen";
header("refresh:2; url=checkout.php");
} else {
echo "Update mislukt";
}
}
当玩家重定向到单独的网页时,将调用函数 checkouttodatabase()。现在我想要的结果是,假设有两个项目添加到购物车数组中。对于添加的每个项目,我希望它将变量发送到 MYSQL 数据库。但我也为总价而奋斗。我想这样做,以便数量乘以添加到 MYSQL 列 Total_price 中的单个 item_price。
例如: 提交时的数据库结果:
商品 ID:商品名称 1,商品数量:3,总价格:45.00$
Item_id:产品名称 2,Item_quantity:1,Total_price:15.00$
最佳答案
在这个代码示例中有一些事情要讨论,但是为了解决将数组放入数据库的问题,@tadman 在上面的评论中给了你答案。在编写 SQL 语句时,不能将数组视为字符串;您需要使用数组的各个元素。
如果您确实想将整个数组保存到 MySQL 数据库表的单个字段中,则必须以某种方式序列化该数组,例如使用 json_encode()
。但是,如果没有令人信服的理由,通常不应将多个值填充到单个数据库列中。
关于PhP 如何将 session 数组发送到 MySQL 表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54405981/