Shopping Cart Logic
हम क्या बना रहे हैं
Shopping cart याद रखता है कि user browse करते हुए क्या खरीदना चाहता है। हम session इस्तेमाल करके एक सरल cart बनाएँगे, ताकि यह checkout तक बिना database pages के बीच बचा रहे। यह items जोड़ेगा, quantities update करेगा, total दिखाएगा, और items हटाएगा।
$_SESSION["cart"] में product id से keyed array के रूप में रहता है, हर एक quantity रखता है।Cart शुरू करना
<?php
session_start();
if (!isset($_SESSION["cart"])) {
$_SESSION["cart"] = []; // खाली cart
}
?>
हम session शुरू करते हैं और पक्का करते हैं cart array मौजूद है। हर cart page ऐसे शुरू होता है ताकि cart हमेशा इस्तेमाल को तैयार रहे।
Cart में जोड़ना
<?php
$id = (int)$_GET["id"]; // product id
if (isset($_SESSION["cart"][$id])) {
$_SESSION["cart"][$id] += 1; // पहले से है: +1
} else {
$_SESSION["cart"][$id] = 1; // नया item
}
echo "Added to cart";
?>
अगर product cart में पहले से है, हम उसकी quantity बढ़ाते हैं; वरना quantity 1 के साथ जोड़ते हैं। id को key बनाना हर product की एक entry रखता है।
Cart और total देखना
<?php
// मान लीजिए prices database से आती हैं:
$prices = [1 => 100, 2 => 250, 3 => 90];
$total = 0;
foreach ($_SESSION["cart"] as $id => $qty) {
$line = $prices[$id] * $qty;
$total += $line;
echo "Product $id x $qty = $line\n";
}
echo "Total: $total";
?>
Total: 200
हम cart में loop करते हैं, हर price भरोसेमंद स्रोत से देखते हैं, quantity से गुणा करते हैं, और total में जोड़ते हैं। browser से भेजी price पर कभी भरोसा न कीजिए।
Item हटाना
<?php
$id = (int)$_GET["id"];
unset($_SESSION["cart"][$id]); // वो product हटाओ
echo "Removed from cart";
?>
unset उस product को cart array से delete करता है। पूरा cart खाली करने को $_SESSION["cart"] = [] set कीजिए।
आम गलतियाँ
- Form से prices पर भरोसा। हमेशा id से database से असली price लाइए।
- id cast न करना। सुरक्षा को
$_GET["id"]को(int)में cast कीजिए। - Duplicate entries। cart को product id से key कीजिए और दोबारा जोड़ने के बजाय quantity बढ़ाइए।
session_start()भूलना। हर cart page को cart पढ़ने को यह चाहिए।
सारांश
- Shopping cart user के browse करते समय session में रहता है।
- इसे product id से keyed array के रूप में रखिए, हर एक quantity के साथ।
- मौजूदा product जोड़ने पर उसकी quantity बढ़ती है।
- Total भरोसेमंद database prices से निकालिए, browser से नहीं।
- Item हटाने को
unset; cart खाली करने को array clear कीजिए।
आगे, अंतिम order save कीजिए PHP CRUD से, या session संभालिए sessions और cookies में।
