Simple PHP Shopping Cart using PHP SESSION
We will create a Simple Shopping Cart using PHP SESSION. eCommerce websites usually uses the PHP session to store items that are added by the user into cart.
Add Cart
<a href="https://example.com/add-items.php?id=1&action=add"> Add to Cart </a>
<?php
$x = array();
@$cart = $_SESSION["shopping_cart"];
if($cart!=""){
foreach($cart as $keys => $values)
{
array_push($x,$values['item_id']);
}
}
if(isset($_GET["action"]))
{
if($_GET["action"] == "add")
{
if(isset($_SESSION["shopping_cart"]))
{
if (!in_array($_GET["id"], $x))
{
end($_SESSION["shopping_cart"]);
$count = key($_SESSION["shopping_cart"]) + 1;
$item_array = array(
'item_id' => $_GET["id"],
'qty' => $_GET["qty"]
);
$_SESSION["shopping_cart"][$count] = $item_array;
echo "<script<?alert('Product added successfully!');</script<";
}
else
{
echo "<script<?alert('Oops.. Product Already Added!');</script<";
}
}
else
{
$item_array = array(
'item_id' => $_GET["id"],
'qty' => $_GET["qty"]
);
$_SESSION["shopping_cart"][0] = $item_array;
echo "<script<?alert('Product added successfully!');</script<";
}
}
}
?>
Delete Cart Item
<?php
<a href="https://example.com/add-items.php?id=1&action=delete"> Add to Cart </a>
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<alert("Product Removed")</script<';
}
}
}
}
?>
Display Cart Item
<?php
foreach($_SESSION["shopping_cart"] as $keys => $values)
{
$b_id = $values["item_id"];
$qty = $values["qty"];
}
?>