【发布时间】:2021-02-11 09:51:05
【问题描述】:
我是 PHP 新手,我从头开始构建了一个页面。 我在网上找到了一个购物车代码,我拿走了并使用它并且工作得很好:
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>';
}
}
}
}
这让我可以将多个产品、数量和价格添加到购物车。 我现在要做的是根据该购买详细信息创建采购订单,假设有人购买了 2 件产品,我需要在 SQL 表中插入 2 行,每个产品一个。
在搜索了一些 Google 之后,我想我必须使用 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";
}
这会返回页面上的下一个错误:
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
我要做的是用数量、总价和单价回显所有产品,看看我是否正确,如果我能做到,那么我有这段代码来执行插入到 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;
}
}
【问题讨论】:
-
如果不完全调试代码,就不可能给出清晰的想法。但错误清楚地说明您正在尝试访问数组的空偏移量