...

View Full Version : Shopping Cart Update Problem



jhl84
07-09-2007, 10:50 AM
Basically I have this shopping cart code. There are 3 cases, add, delete and update items in my shopping cart. My problem is with the update part. How can I make sure qty can never be 0 or -1? If it is 0 or less, it automatically sets to 1 again. $key is item_number while $value is quantity. Thanks



<?php
session_start();
// Process actions
$cart = $_SESSION['cart'];
$action = $_GET['action'];
switch ($action) {
case 'add':
if ($cart) {
$cart .= ','.$_GET['item_number'];
} else {
$cart = $_GET['item_number'];
}
break;
case 'delete':
if ($cart) {
$items = explode(',',$cart);
$newcart = '';
foreach ($items as $item) {
if ($_GET['item_number'] != $item) {
if ($newcart != '') {
$newcart .= ','.$item;
} else {
$newcart = $item;
}
}
}
$cart = $newcart;
}
break;
case 'update':
if ($cart) {
$newcart = '';
foreach ($_POST as $key=>$value) {
if (stristr($key,'qty')) {
$item_number = str_replace('qty','',$key);
$items = ($newcart != '') ? explode(',',$newcart) : explode(',',$cart);
$newcart = '';
foreach ($items as $item) {
if ($item_number != $item) {
if ($newcart != '') {
$newcart .= ','.$item;
} else {
$newcart = $item;
}
}
}
for ($i=1;$i<=$value;$i++) {
if ($newcart != '') {
$newcart .= ','.$item_number;
} else {
$newcart = $item_number;
}
}
}
}
}
$cart = $newcart;
break;
}
$_SESSION['cart'] = $cart;
?>

Fumigator
07-09-2007, 05:11 PM
if ($value < 1) {
$value = 0;
}

aedrin
07-09-2007, 06:55 PM
$items = explode(',',$cart);

This is a very bad way of storing items. It's not clean, it requires you to constantly 'pack' and 'unpack' the variable, which makes it a lot easier to lose information. Not to mention you're constantly writing extra code just to convert (harder to read and costs more to code.)

I'd recommend storing them as such (in a most simplistic form):



$cart = array(
'100' => 5, // 5 of product no. 100
'102' => 2 // 2 of product no. 102
// etc.
);


Of course you wouldn't create the array like that, but what you end up with is how you would store it.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum