Shopping Cart Array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Parmenion
Forum Commoner
Posts: 35
Joined: Sat Dec 12, 2009 8:29 am

Shopping Cart Array

Post by Parmenion »

Hi guys,

I'm having some problems with a shopping cart array that will hold the items and struggling to get it to work as I want.

It's for a photography site to sell photos in a variety of size prints. I have the photo details stored in one table with the sizes and prices in a separate table.

On the individual photo page I have an add to cart button, which sends the photo id, size and price to a new page.

I've been trying to get the details into an array with some success but it's not working quite like I want and I can't iterate the details into a table as I want to either.

A session is set up for the cart as $_SESSION['cart']. A session is also set up to store the total quantities as $_SESSION['qty'].

Here's my code so far:

Code: Select all

 
if (isset($_GET['new']))
    {
        $photo_id = $_POST['id'];
        $photo_size = $_POST['size'];
        $price = $_POST['price'];
        
        if (isset($_SESSION['cart']))
            {
                $items = array($_SESSION['cart']);
                
            }
            else
            {
                $items = array();
            }
            
        if (isset($_SESSION['qty']))
            {
                $item_qty = $_SESSION['qty'];
            }
            else
            {
                $item_qty = 0;
            }
        
        array_push($items, $photo_id, $photo_size, $price);
        $_SESSION['cart'] = $items;
        $_SESSION['qty'] = ++$item_qty;
        header("Location: view_cart.php?cart");
 
I'm not sure my methods are the best for this and any help would be appreciated. Is there a way to set up a two-dimensional array and give each element a name but also push new items to the array?
User avatar
s.dot
Tranquility In Moderation
Posts: 5001
Joined: Sun Feb 06, 2005 7:18 pm
Location: Indiana

Re: Shopping Cart Array

Post by s.dot »

Here's how I would code something like that. I put in comments for you to read.

Code: Select all

<?php
 
if (isset($_GET['new']))
{
    $photo_id = $_POST['id'];
    $photo_size = $_POST['size'];
    $price = $_POST['price'];
    
    //make sure we have an array for the cart
    if (!isset($_SESSION['cart']))
    {
        $_SESSION['cart'] = array();
    }
    
    //now we just add an element to the array
    $_SESSION['cart'][] = array('id' => $photo_id, 'size' => $photo_size, 'price' => $price);
    
    //not really sure what you're doing with quanity here?
    //is this the quantity of photos they want or the number of 
    //items in their cart?
    $_SESSION['qty'] = ++$_SESSION['qty'];
    
    header("Location: view_cart.php?cart");
         
}
This way if you were to look at $_SESSION['cart'] it would look like this:

Code: Select all

Array (
    Array (
        id => photo1_id,
        size => photo1_size,
        price => photo1_price
    ),
    Array (
        id => photo2_id,
        size => photo2_size,
        price => photo2_price
    )
)
This would make viewing the cart extremely easy with sample code like:

Code: Select all

if (!empty($_SESSION['cart']))
{
    foreach ($_SESSION['cart'] AS $item)
    {
        echo 'Photo ID: ' . $item['id'] . '<br />
        Size: ' . $item['size'] . '<br />
        Price: ' . $item['price'] . '<br /><br />';
    }
}
And counting the number of items in the cart would be as easy as:

Code: Select all

$numitems = count($_SESSION['cart']);
echo $numitems;
Also, you may not have posted the full code so you might already have it in there, but just in case - you have to call session_start(); before you can deal with sessions.
Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
Parmenion
Forum Commoner
Posts: 35
Joined: Sat Dec 12, 2009 8:29 am

Re: Shopping Cart Array

Post by Parmenion »

Thanks very much for you help, s.dot.

I've tested it out and it works a lot better now. I had an session array for quantity because the way I had the array setup it wasn't counting the actually number of photos in the cart properly.

I had started a session but just hadn't posted that bit.

The next thing I would like to do is combine any photos of the same size and add a form field with the quantity written next to it like:

Photo Name 1 Size 6"x4" Qty 4
Photo Name 1 Size 7.5"x5" Qty 1

Would I add a quantity value to the cart array and then have an if statement that increases the quantity by 1 if the photo id is already in the array somewhere?
User avatar
s.dot
Tranquility In Moderation
Posts: 5001
Joined: Sun Feb 06, 2005 7:18 pm
Location: Indiana

Re: Shopping Cart Array

Post by s.dot »

That would be very easy to do :)

Have a qty form field

Code: Select all

$qty = $_POST['qty'];
 
$_SESSION['cart'][] = array('id' => $photo_id, ..................., 'qty' => $qty);
To check if they're adding a photo that's already in the cart use in_array().
Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
Parmenion
Forum Commoner
Posts: 35
Joined: Sat Dec 12, 2009 8:29 am

Re: Shopping Cart Array

Post by Parmenion »

That's not exactly what I meant, s.dot, although thanks for the reply.

When the customer clicks the shopping cart link I would like to list the items in the cart and have a facility to update the quantities on that page. I'm guessing I'll need to iterate the cart items differently so that I can add a form for the customer to change quantities. I'll need a form next to each order line and will have an update button that when clicked will search the array for the correct item and adjust the quantity accordingly.
Parmenion
Forum Commoner
Posts: 35
Joined: Sat Dec 12, 2009 8:29 am

Re: Shopping Cart Array

Post by Parmenion »

I've made a bit of progress but unsure how to do the next part. My code so far:

Code: Select all

 
<?php
session_start();
 
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'];
    
    //make sure we have an array for the cart
    if (!isset($_SESSION['cart']))
    {
        $_SESSION['cart'] = array();
    }
 
    //now we just add an element to the array
    $_SESSION['cart'][] = 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");
}
?>
 

Code: Select all

 
if (!empty($_SESSION['cart']))
    {
    echo '<table width="500px" border="1" bordercolor="#999999" cellpadding="5">';
    echo '<tr>';
    //echo '<th bgcolor="#ff7400"><font color="#ffffff">Photo Id</font></th>';
    echo '<th bgcolor="#ff7400"></th>';
    echo '<th bgcolor="#ff7400"><font color="#ffffff">Photo Name</font></th>';
    echo '<th bgcolor="#ff7400"><font color="#ffffff">Size</font></th>';
    echo '<th bgcolor="#ff7400"><font color="#ffffff">Item Price</font></th>';
    echo '<th bgcolor="#ff7400"><font color="#ffffff">Qty</font></th>';
    echo '<th bgcolor="#ff7400"></th>';
    echo '<th bgcolor="#ff7400"></th>';
    echo '</tr>';
    for ($row = 0; $row < count($_SESSION['cart']); $row++)
    {
        echo '<tr>';
        //echo '<td colspan="1">' .$_SESSION['cart'][$row]['id']. '</td>';
        echo "<td colspan='1'><img src='".($_SESSION['cart'][$row]['photo'])."' width='110px' alt='".($_SESSION['cart'][$row]['name'])."' /></td>";
        echo '<td colspan="1">' .$_SESSION['cart'][$row]['name']. '</td>';
        echo '<td colspan="1">' .$_SESSION['cart'][$row]['size']. '</td>';
        echo '<td colspan="1">' .$_SESSION['cart'][$row]['price']. '</td>';
        echo '<td colspan="1"><form action="view_cart.php?update" method="post"><input type="text" size="1" name="qty" value="' .($_SESSION['cart'][$row]['qty']). '"></td>';
        echo '<td colspan="1"><input type="submit" name="submit" value="Update"></form></td>';
        echo '<td colspan="1"><form action="view_cart.php?remove" method="post"><input type="hidden" size="1" name="photoId" value="' .($_SESSION['cart'][$row]['photoId']). '"><input type="hidden" size="1" name="sizeId" value="' .($_SESSION['cart'][$row]['sizeId']). '"><input type="submit" name="submit" value="Remove"></form></td>';
        echo '</tr>';
    }
    echo '</table>';
    }
    else
    {
        echo "No items to display";
    }
 
?>
 
I have an update button and a remove button by each item in the cart. I want to update/delete from the array but how can I select a particular element in the array and change it or remove the row totally?

I think the in_array function would check if that item is in the array but I don't know how to alter the array.

In the array I have a photo id and size id, which I hope to use to identify a particular photo and size.
Parmenion
Forum Commoner
Posts: 35
Joined: Sat Dec 12, 2009 8:29 am

Re: Shopping Cart Array

Post by Parmenion »

Anyone know how it can be done? :(
Kurby
Forum Commoner
Posts: 63
Joined: Tue Feb 23, 2010 10:51 am

Re: Shopping Cart Array

Post by Kurby »

Perhaps you want array_search instead of in_array?
Parmenion
Forum Commoner
Posts: 35
Joined: Sat Dec 12, 2009 8:29 am

Re: Shopping Cart Array

Post by Parmenion »

I've just given array_search a go but it doesn't work.

The code I used:

Code: Select all

 
$photo_id = $_POST['photoId'];
$array = $_SESSION['cart'];
$key = array_search($photo_id, $array);
echo $key;
 
It doesn't return any value though. I think it must be because I'm using a two-dimensional array.

I also tried this hoping it would change just a single row but it changes every quantity in the cart:

Code: Select all

 
$newqty = $_POST['qty'];
for ($row = 0; $row < count($_SESSION['cart']); $row++)
        {
            $_SESSION['cart'][$row]['qty'] = $newqty;
        }
 
I don't know enough about PHP so just don't know what to do.
Parmenion
Forum Commoner
Posts: 35
Joined: Sat Dec 12, 2009 8:29 am

Re: Shopping Cart Array

Post by Parmenion »

If it helps the array is structured like this:

Array ( [0] => Array ( [photoId] => 1 [photo] => elements/photos/agingface.jpg [name] => Aging Face [sizeId] => 2 [size] => 10x15cm (4" x 6") Print [price] => 5.99 [qty] => 3 ) )

I've spent ages trying things out but nothing works. Am I simply doing it all the wrong way and it won't work regardless? If there's a better way to do a shopping cart I'd love to know.
Kurby
Forum Commoner
Posts: 63
Joined: Tue Feb 23, 2010 10:51 am

Re: Shopping Cart Array

Post by Kurby »

Parmenion
Forum Commoner
Posts: 35
Joined: Sat Dec 12, 2009 8:29 am

Re: Shopping Cart Array

Post by Parmenion »

Had another play and managed to get it to work. I can now update the quantity and it updates only the one I selected.

I had an include inside the for loop, which was causing problems and by placing it outside the loop it helped things.

For those interested here's my code:

Code: Select all

 
<?php
 
if(isset($_GET['update']))
    {
    $newqty = $_POST['qty'];
    $photo_id = $_POST['photoId'];
    $size_id = $_POST['sizeId'];
 
    for ($row = 0; $row < count($_SESSION['cart']); $row++)
    {
        if (($_SESSION['cart'][$row]['photoId'] == $photo_id) && ($_SESSION['cart'][$row]['sizeId'] == $size_id))
        {   
            if ($_SESSION['cart'][$row]['qty'] > $newqty)
            {
                $difference = $_SESSION['cart'][$row]['qty'] - $newqty;
                $_SESSION['qty'] = $_SESSION['qty'] - $difference;
            }
            elseif ($_SESSION['cart'][$row]['qty'] < $newqty)
            {
                $difference = $newqty - $_SESSION['cart'][$row]['qty'];
                $_SESSION['qty'] = $_SESSION['qty'] + $difference;
            }
            else
            {
                $_SESSION['qty'] = $_SESSION['qty'];
            }
                    
            
            $_SESSION['cart'][$row]['qty'] = $newqty;
        }
    }
    header("Location: view_cart.php");
    }
 
?>
 
Haven't had a look at the link yet, Kurby, but thanks for posting it. It may help at a later stage.
User avatar
s.dot
Tranquility In Moderation
Posts: 5001
Joined: Sun Feb 06, 2005 7:18 pm
Location: Indiana

Re: Shopping Cart Array

Post by s.dot »

I would set the photo id as the array key in the cart when adding items

Code: Select all

$_SESSION['cart'][$photoid] = array('id' => $photoid, 'size' => $size);
Then you could easily set the qty by doing

Code: Select all

$photoid = 3;
 
$_SESSION['cart'][$photoid]['qty'] = 'x';
Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
Parmenion
Forum Commoner
Posts: 35
Joined: Sat Dec 12, 2009 8:29 am

Re: Shopping Cart Array

Post by Parmenion »

Removing a row is causing a few issues.

I'm using this code:

Code: Select all

 
if(isset($_GET['remove']))
    {
    $photo_id = $_POST['photoId'];
    $size_id = $_POST['sizeId'];
 
    for ($row = 0; $row < count($_SESSION['cart']); $row++)
    {
        if (($_SESSION['cart'][$row]['photoId'] == $photo_id) && ($_SESSION['cart'][$row]['sizeId'] == $size_id))
        {
            unset($_SESSION['cart'][$row]);
        }
    }
    header("Location: view_cart.php");
    }
 
It deletes the rows fine UNLESS I delete the first item in the array, which it doesn't like. I need to find a way around it.
Parmenion
Forum Commoner
Posts: 35
Joined: Sat Dec 12, 2009 8:29 am

Re: Shopping Cart Array

Post by Parmenion »

Ok, it deletes each row without throwing an error after I added the line below.

Code: Select all

 
reset($_SESSION['cart'][$row]); 
 
Problem is, it now leaves an empty sub array like this:

Code: Select all

 
Array
(
    [0] => Array
        (
            [photoId] => 1
            [photo] => elements/photos/agingface.jpg
            [name] => Aging Face
            [sizeId] => 1
            [size] => 9X13cm (3.5"x5") Print
            [price] => 3.99
            [qty] => 1
        )
 
    [2] => Array
        (
            [photoId] => 1
            [photo] => elements/photos/agingface.jpg
            [name] => Aging Face
            [sizeId] => 4
            [size] => 20x27cm (8" x 10.6") Print
            [price] => 9.99
            [qty] => 1
        )
 
    [1] => 
)
 
Is there a way to remove the empty sub array?
Post Reply