Page 2 of 2
Re: Shopping Cart Array
Posted: Thu Mar 04, 2010 12:49 pm
by Parmenion
I've fixed one of the problems. It now deletes a selected photo from the cart no matter where it is in the array. I simply changed the for loop for a foreach loop. It removes the row totally and doesn't leave an empty shell.
Still need to sort the following:
- Add up a total amount in the cart
Tell it to add a just quantity if photo in same size is already in the cart
I had mixed success with the recursive array search from Kurby's link.
It's getting there slowly.
Re: Shopping Cart Array
Posted: Thu Mar 04, 2010 4:49 pm
by Parmenion
Thanks for showing me how to define an array key by the way, s.dot, it's helped a lot. I gave each photo and size a unique key by joining the two into a new variable. It works great and means photos of the same type and size don't get duplicated.
Still working on a few issues but will report back.
My code for adding photos to the cart:
Code: Select all
if (isset($_GET['new']))
{
$photo_id = $_POST['photoId'];
$connection = mysql_connect('localhost', 'user', 'password') or die ('Unable to connect!');
mysql_select_db('db') or die ('Unable to select database!');
$result = mysql_query("SELECT * FROM shop_items WHERE id = $photo_id");
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$photo_link = $row['photo_link'];
$photo_name = $row['photo_name'];
}
$size_id = $_POST['sizeId'];
$photo_size = $_POST['size'];
$price = $_POST['price'];
$qty = $_POST['qty'];
$item_id = $photo_id . $size_id; //Create an index for each photo and size
//make sure we have an array for the cart
if (!isset($_SESSION['cart']))
{
$_SESSION['cart'] = array();
}
if (array_key_exists($item_id, $_SESSION['cart']))
{ //If the key already exists
$row = $item_id; //Find the correct row
$_SESSION['cart'][$row]['qty'] = $_SESSION['cart'][$row]['qty'] + $qty; //Increase the quantity
$_SESSION['qty'] = $_SESSION['qty'] + $qty;
}
else
{ //Else add to cart
$_SESSION['cart'][$item_id] = array('photoId' => $photo_id, 'photo' => $photo_link, 'name' => $photo_name, 'sizeId' => $size_id, 'size' => $photo_size, 'price' => $price, 'qty' => $qty);
$_SESSION['qty'] = $_SESSION['qty'] + $qty;
}
unset ($_GET['new']);
mysql_free_result($result);
mysql_close($connection);
header("Location: view_cart.php");
}
?>
I thought the code might help someone else so hope it's of use.
Re: Shopping Cart Array
Posted: Fri Mar 05, 2010 8:32 am
by Parmenion
Anyone know how I can add these up?
Code: Select all
Array
(
[11] => Array
(
[lineTotal] => 3.99
)
[12] => Array
(
[lineTotal] => 5.99
)
[14] => Array
(
[lineTotal] => 19.98
)
)
I read about array_sum but it doesn't work in my case.
Re: Shopping Cart Array
Posted: Fri Mar 05, 2010 2:34 pm
by Parmenion
Nevermind, I sorted it myself. The cart is now finished.