Skip to content
Advertisement

i want to increase cart quantity php every time add to cart is clicked. I checked few provided solutions but none of them worked

<?php
session_start();
if (isset($_GET) & !empty($_GET)) {
    $id = $_GET['id'];
    $url = $_GET['sourceurl'];
if (isset($_GET['quant']) & !empty($_GET['quant'])) {
    $quant = $_GET['quant'];
} else {
    $quant = 1;
}
$_SESSION['cart'][$id] = array("quantity" => $quant);
//header('location:' . $url);
//header('location:index.php?message=1');
} else {
//header('location:' . $url);
}
echo "<pre>";
print_r($_SESSION['cart']);
echo "</pre>";

I have common php page addtocart.php to add product directly to cart from homepage and also from single.php where user can add quantity. If quantity is not given(i.e adding to cart from index page) quantity is directly set to 1. Here I want to increase quanity every time user clicks on addtocart. Above is the code of addtocart.php

Advertisement

Answer

Replace $_SESSION['cart'][$id] = array("quantity" => $quant); for this oneliner.

$_SESSION['cart'][$id]['quantity'] = ((isset($_SESSION['cart'][$id]['quantity'])) && ($_SESSION['cart'][$id]['quantity'] > 0)) ? ++$_SESSION['cart'][$id]['quantity'] : $quant;
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement