📘 Lesson  ·  Lesson 43

Shopping Cart Logic

Shopping Cart Logic

About

A shopping cart stores selected products in the session so they stay while the user browses. Here is the core logic.

Add to Cart

session_start();
$id = $_GET["id"];
if (!isset($_SESSION["cart"][$id])) {
    $_SESSION["cart"][$id] = 1;       // quantity
} else {
    $_SESSION["cart"][$id]++;
}
echo "Added to cart";

View Cart

foreach ($_SESSION["cart"] as $id => $qty) {
    echo "Product $id x $qty<br>";
}

Remove Item

unset($_SESSION["cart"][$_GET["id"]]);
echo "Removed";

Summary

  • Store cart items in $_SESSION["cart"] as id => quantity.
  • Add increments quantity; unset removes an item.

परिचय

Shopping cart चुने products को session में रखता है ताकि user के browse करते समय वे बने रहें। यह रहा core logic।

Cart में Add करें

session_start();
$id = $_GET["id"];
if (!isset($_SESSION["cart"][$id])) {
    $_SESSION["cart"][$id] = 1;       // quantity
} else {
    $_SESSION["cart"][$id]++;
}
echo "Added to cart";

Cart देखें

foreach ($_SESSION["cart"] as $id => $qty) {
    echo "Product $id x $qty<br>";
}

Item हटाएं

unset($_SESSION["cart"][$_GET["id"]]);
echo "Removed";

सारांश

  • Cart items को $_SESSION["cart"] में id => quantity के रूप में रखें।
  • Add quantity बढ़ाता है; unset item हटाता है।
← Back to PHP Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

Is page ki language (PHP) mein code likhein aur turant chalाएं — yahीं, bina kuch install kiye.
Powered by OneCompiler. Agar editor na khule to yahान naye tab mein kholein.

💻 Live Code Editor

Is page ke program yahan ready hain — chalाएं, badlें aur seekhें. Bina kuch install kiye.
Powered by OneCompiler. Editor mein code apne aap aa jata hai — Run dabaakर output dekhें. Agar load na ho to naye tab mein kholें.