你能告诉我如何在购物车中对相同的物品进行分组吗?有必要确保相同的产品(具有相同的 id)在添加到购物车时会增加其价格和数量,而不是作为新产品添加。尝试了 GROUP BY 和计数,GROUP_CONTACT,但不明白为什么它不起作用。我希望能得到你的帮助!
<?php
session_start();
require $_SERVER['DOCUMENT_ROOT'].'/config/safemysql.class.php';
$db = new safeMysql();
$action = $_POST["action"];
if ($action == 'show'){
if (!(isset($_SESSION['cart']))){
echo 'У вас нет заказов. Корзина пуста!';
exit;
};
$cart = $_SESSION['cart'];
if (count($cart) == 0){
echo 'У вас нет заказов. Корзина пуста!';
exit;
}
for ($i = 0; $i < count($cart); $i++){
$idProduct = $cart[$i]["idProduct"];
$result = $db->query('SELECT products.*, gallery.* FROM products INNER JOIN gallery on products.id=gallery.id_products WHERE id_products = '.$cart[$i]["idProduct"].' LIMIT 1');
while ($row = $db->fetch($result)){
echo'
<div class="card" id="card">
<a class="card__link" href="#">
<div class="card__images">
<img class="card__image" src="content/products/'.$row["image"].'" width="214" height="162" alt="" />
</div><!-- .card__images -->
</a>
<a class="card__title" href="#">'.$row["name"].'</a>
<div class="card__footer">
<p class="card__price">'.$row["price"].'</p>
<div class="card__quantity">
<div class="quantity">
<button class="quantity__minus" type="button" aria-label="-1"></button>
<input class="quantity__input" type="text" value="1" />
<button class="quantity__plus" type="button" aria-label="+1"></button>
</div><!-- .quantity -->
<button class="card__delete" type="button" onClick="delFromCart('.$row["id_products"].')">Удалить</button>
</div><!-- .card__quantity -->
</div><!-- .card__footer -->
</div><!-- .card -->
';
}
}
}
############################
if ($action == 'add'){
$cart = $_SESSION['cart'];
$id = $_POST['id'];
$newProduct["idProduct"] = $id;
$cart[count($cart)] = $newProduct;
$_SESSION['cart'] = $cart;
}
###########################
if ($action == 'del'){
$id = $_POST["id"];
$newCart = array();
$cart = $_SESSION['cart'];
for ($i = 0; $i < count($cart); $i++){
$idProduct = $cart[$i]["idProduct"];
if ($id != $idProduct){
$newCart[count($newCart)] = $cart[$i];
}
}
$_SESSION['cart'] = $newCart;
}
?>
你这里一切都错了。
从将商品添加到购物车的错误代码开始。而不是多达五行应该有一个,
没有所有这些从空变为空。
如果你仔细想想,篮子应该是一个二维数组,其中键是产品 id,值是数量。
之后,您不必在查询中对任何内容进行分组
始终将别名链接到表。
在分组和输出中(在 select-e 中),您应该具有相同的字段,至少是因为来自产品的多个记录对应于您的一个购物篮。您还可以在 select-e 中看到那些不参与分组的字段,但只能通过某种列表,例如。