简体   繁体   English

从会话购物车中读取多个项目时出现问题

[英]Problem when reading multiple items from session shopping cart

I'm kind of new to PHP and I built a page from scratch.我对 PHP 有点陌生,我从头开始构建了一个页面。 I found out a shopping cart code online which I took and use and works perfectly fine:我在网上找到了一个购物车代码,我拿来使用,效果很好:

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"]
            );
            $_SESSION["shopping_cart"][$count] = $item_array;
        }
        else
        {        }
        
    }
    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;
    }
}

if(isset($_GET["action"]))
{
    if($_GET["action"] == "delete")
    {
        foreach($_SESSION["shopping_cart"] as $keys => $values)
        {
            if($values["item_id"] == $_GET["id"])
            {
                unset($_SESSION["shopping_cart"][$keys]);
                echo '<script>window.location="grid.php"</script>';
            }
        }
    }
} 

This let me add multiple products, quantity and price to a cart.这让我可以将多个产品、数量和价格添加到购物车。 What I'm now trying to do is create purchase orders from that purchase detail, lets say someone buys 2 products, I need to insert into SQL table 2 rows, one for each product.我现在要做的是从该采购明细创建采购订单,假设有人购买了 2 个产品,我需要插入 SQL 表 2 行,每个产品一个。

after some Google, I figured I'd have to use a foreach and I ended up with this:经过一些谷歌,我想我必须使用 foreach ,我最终得到了这个:

$_SESSION['shopping_cart'][] = $result;
foreach ($_SESSION['shopping_cart'] as $result){
    echo "Item id:  ".$result['item_id']." , <br>\n 
          cantidad: ".$result['item_quantity']." ,<br>\n 
          Precio unitario: ".$result['item_price']."<br>\n";
}

this returns the next error on the page :这将返回页面上的下一个错误:


Notice: Trying to access array offset on value of type null in C:\xampp\htdocs\PHP\Proyecto\Crear_OC.php on line 79

Notice: Trying to access array offset on value of type null in C:\xampp\htdocs\PHP\Proyecto\Crear_OC.php on line 80

what I'm trying to do is echo all the products with quantity, total and unit price to see if I was getting them right, if I can do that then I have this code to execute the inserts into SQL :我想要做的是回显所有产品的数量、总价和单价,看看我是否做对了,如果我能做到,那么我有这个代码来执行插入到 SQL 中:

$total = $total + ($values["item_quantity"] * $values["item_price"]);
    $sql="  INSERT INTO ordenes_ventas (ID_Producto,ID_Cliente,Precio_Unitario,Cantidad,Monto)
                    select p.ID_Producto,C.ID_Cliente,p.Precio_Unidad, $result['item_quantity'],$total 
                    from productos p 
                    join clientes c 
                    on c.ID_Cliente = (select c.ID_Cliente from clientes c where c.Users = '$user') 
                    where p.ID_Producto = $result['item_id'] ";

    if ($conexion->query($sql) === TRUE) {
    echo 'Succesful!';
    } else {
    echo "Error: " . $sql . "<br>" . $conexion->error;
}
}

What you want to do is to use the session number in the shopping cart and perform a MySQL statement to find the items that the customer has been shopping for.您想要做的是使用购物车中的会话号并执行 MySQL 语句来查找客户一直在购买的商品。 This insures that if two customers are using the cart at the same time their orders aren't confused and load at the same time.这确保如果两个客户同时使用购物车,他们的订单不会混淆并同时加载。

I am including some code I have done on a project that you can look at to incorporate into your code.我包含了我在一个项目中完成的一些代码,您可以查看这些代码并将其合并到您的代码中。

You need to capture the session number for the individual:您需要捕获个人的会话编号:

/*insert the content into the cart table*/
        $addCart = 'INSERT INTO cart (cartId, productId, quantity_order, sessionNumber) VALUES ("","'.$productId.'","'.$quantity.'","'.$sessionNumber.'")';

After you have the items in your cart you can now use another SQL statement to find the current items in the customers cart.将商品放入购物车后,您现在可以使用另一个 SQL 语句查找客户购物车中的当前商品。

$findCart = "SELECT p.productId, p.name, p.image, p.price, p.quantity, c.cartId, c.quantity_order, c.sessionNumber FROM product p, cart c WHERE p.productId = c.productId AND c.sessionNumber = '$sessionNumber' "; 

I think this method will be much smoother than an array statement.我认为这种方法会比数组语句流畅得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM