Shopping Cart

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

Post Reply
bob_the _builder
Forum Contributor
Posts: 131
Joined: Sat Aug 28, 2004 12:25 am

Shopping Cart

Post by bob_the _builder »

Hi,

I am using the following code to generate a shoping cart. Right now I am trying to run the code using an array created on page rather than pulling data from database.

How should the code be formated to grab data from an array on the page instead?

Code: Select all

<?php

case 'addcart':

	if (is_numeric($_GET['id'])) {
	$itemid = $_GET['id'];
	if (isset($_SESSION['cart'][$itemid])) {
	$qty = $_SESSION['cart'][$itemid] + 1;
	}else{
	$qty = $_GET['qty'];
	}
	$_SESSION['cart'][$itemid] = $qty;
	header("location: ../store.php");
	}

break;

case 'cart';

	if(isset($_POST['submit'])){
	foreach($_REQUEST['qty'] as $key => $value){
	if (($value == 0) && (is_numeric ($value))){
	unset ($_SESSION['cart'][$key]);
	}elseif ( is_numeric ($value) AND ($value > 0) ){
	$_SESSION['cart'][$key] = $value;
	  }
	 }
	}

	$empty = TRUE;
	if(isset($_SESSION['cart'])) {
	foreach ($_SESSION['cart'] as $key => $value) {
	if(isset($value)) {
	$empty = FALSE;	
	  }
	 } 
	}	

	if(!$empty) {
	$query = 'SELECT * FROM items WHERE itemid IN (';
	foreach($_SESSION['cart'] as $key => $value) {
	$query .= $key . ',';
	}
	$query = substr ($query, 0, -1) . ') ORDER BY itemid ASC';
	$result = mysql_query($query);

	// Start form to display content headings
	
	$total = 0;
	while ($row = mysql_fetch_array ($result)) {
	foreach($row as $key=>$value){
	$$key = ValidateInput($value);
	}

	$subtotal = $_SESSION['cart'][$itemid] * $price;
	$total += $subtotal;
		
	$qty = $_SESSION['cart'][$itemid];
	$totalqty += $qty;

	session_register('total');
	$_SESSION['total'] = number_format($total, 2);

	session_register('qty');
	$_SESSION['qty'] = $qty;

	session_register('totalqty');
	$_SESSION['totalqty'] = $totalqty;
						
	// loop through carts records and display
	
	}
	
	// End form to display	
		
	}else{
	echo '<p /><center>Your cart is currently empty.</center>';
	}

break;

?>
User avatar
aceconcepts
DevNet Resident
Posts: 1424
Joined: Mon Feb 06, 2006 11:26 am
Location: London

Post by aceconcepts »

Using an array instead of a db table simply requires you to store cart data relative to a unique identifier i.e. session_id.

Take a look at http://uk3.php.net/array_combine

However this is a PHP 5 function. You can find ways to use it with earlier versions though.
bob_the _builder
Forum Contributor
Posts: 131
Joined: Sat Aug 28, 2004 12:25 am

Post by bob_the _builder »

Hi,

Yer I realise thats the concept, but im not having much luck making it happen.

I have the array created, and list the items using:

Code: Select all

echo '<table>';
	foreach($items as $i) {
	echo '<tr>
	<td>
	'.$i['ItemName'].' $'.number_format($i['ItemPrice'],2).'
	<b><a href="num_items.php?ItemID='.$i['ItemID'].'">Add Item</a></b>
	</td>
	</tr>';
	}
	echo '</table><p />
The problem im having is displaying the the array items that have been added to the cart. I have tried a few ways but nothing has wored so far:

Code: Select all

if(isset($_POST['submit'])){ 
        foreach($_REQUEST['qty'] as $key => $value){ 
        if (($value == 0) && (is_numeric ($value))){ 
        unset ($_SESSION['cart'][$key]); 
        }elseif ( is_numeric ($value) AND ($value > 0) ){ 
        $_SESSION['cart'][$key] = $value; 
          } 
         } 
        } 

        $empty = TRUE; 
        if(isset($_SESSION['cart'])) { 
        foreach ($_SESSION['cart'] as $key => $value) { 
        if(isset($value)) { 
        $empty = FALSE;  
          } 
         } 
        }        

        if(!$empty) { 

       // Start form to display content headings 
        
        $total = 0; 

        foreach($_SESSION['cart'] as $items=>$i) {

        $subtotal = $_SESSION['cart'][$itemid] * $i['price']; 
        $total += $subtotal; 
                
        $qty = $_SESSION['cart'][$itemid]; 
        $totalqty += $qty; 

        session_register('total'); 
        $_SESSION['total'] = number_format($total, 2); 

        session_register('qty'); 
        $_SESSION['qty'] = $qty; 

        session_register('totalqty'); 
        $_SESSION['totalqty'] = $totalqty; 
                                                
        // loop through carts records and display 
        
        } 
        
        // End form to display  
                
        }else{ 
        echo '<p /><center>Your cart is currently empty.</center>'; 
        }
That seems to show the correct amount of lines for items added to the cart, but doesnt display any of the contents .. just the numeral 1 in place where the data should be.

Thanks
User avatar
Stryks
Forum Regular
Posts: 746
Joined: Wed Jan 14, 2004 5:06 pm

Post by Stryks »

I'm having a little trouble making heads or tails out of what you have posted.

One thing that jumps out at me though is ...

Code: Select all

        foreach($_SESSION['cart'] as $items=>$i) {

        $subtotal = $_SESSION['cart'][$itemid] * $i['price'];
        $total += $subtotal;
               
        $qty = $_SESSION['cart'][$itemid];
        $totalqty += $qty; 
I think you might have accidentally used $itemid in the last 4 lines instead of $items specified in the first. Or maybe not.

Also, those calls to session_register inside the foreach loop are going to overwrite the values for each cart item, ie. always show the last set of values.


Have you had a look at this post?

Having a re-read, maybe I misunderstand what you are asking. I'll think further on it.
User avatar
Stryks
Forum Regular
Posts: 746
Joined: Wed Jan 14, 2004 5:06 pm

Post by Stryks »

I think that perhaps the solution might be best found if we nail down exactly what you're trying to do here?

You say that you usually grab the data from a database, but you are trying to use the same approach but with an array from a page. I'm confused about where the array is coming from? I mean, are you making the array manually? ie.

Code: Select all

$myArray = array('something', 'else');
Or are you referring to an array of form elements?

I'll go re-read your posts to see what I can see ... but yeah .. a bit of an idea of what you are actually doing might help.

/*** EDIT
What's the deal with that first code snippet? Is it just me, or are you missing the switch() call for those case statements? I thought it was just a cutting error, but then I notices you have php open and close tags. What gives with that?
bob_the _builder
Forum Contributor
Posts: 131
Joined: Sat Aug 28, 2004 12:25 am

Post by bob_the _builder »

Array is built:

Code: Select all

$items = array();
	$items[1] = array("ItemID"=>1,"ItemName"=>"Chicken Burger","ItemPrice"=>5.00);
	$items[2] = array("ItemID"=>2,"ItemName"=>"Veal Schnitzel","ItemPrice"=>7.50);
	$items[3] = array("ItemID"=>3,"ItemName"=>"Onion Rings","ItemPrice"=>3.00);
	$items[4] = array("ItemID"=>4,"ItemName"=>"Nachos","ItemPrice"=>5.50);
	$items[5] = array("ItemID"=>5,"ItemName"=>"Hot Potato","ItemPrice"=>4.00);
	$items[6] = array("ItemID"=>6,"ItemName"=>"Salad Sandwich","ItemPrice"=>4.00);
	$items[7] = array("ItemID"=>7,"ItemName"=>"Macaroni Cheese","ItemPrice"=>3.50);
	$items[8] = array("ItemID"=>8,"ItemName"=>"Bacon and Eggs","ItemPrice"=>7.50);
the first block of code posts to another page where the number of that items is selected then gets posted to nex page which adds items to cart:

Code: Select all

// Start session
	session_start();

	// Add item to cart
	if(is_numeric($_POST['ItemID'])) {
	$ItemID = $_POST['ItemID'];
	if (isset($_SESSION['cart'][$ItemID])) {
	$qty = $_SESSION['cart'][$ItemID] + $_POST['qty'];
	}else{
	$qty = $_POST['qty'];
	}

	$_SESSION['cart'][$ItemID] = $qty;
	header("location: show_cart.php");
	}
At this stage it posts to seperate pages for the project.. normally I have it all within functions.

Thanks
User avatar
Stryks
Forum Regular
Posts: 746
Joined: Wed Jan 14, 2004 5:06 pm

Post by Stryks »

Well .... from what I can see there, if you add an item to the cart, and then did ... say ...

Code: Select all

foreach($_SESSION['cart'] as $itemId=>$itemQty) echo "You have ordered $itemQty x $itemId";
On the second page, thats pretty much all the data you have access to. If you want more than that, you'll have to redesign a little.

For example, if you want to re-access what the item is from the original array, you'll have to either remake the array and reference it with $itemId, or actually save the items details into the cart array.

As it stands, the only data you are putting into your cart is the itemID and the quantity.

Is this not what you wanted? If not, what was it that you were after?
bob_the _builder
Forum Contributor
Posts: 131
Joined: Sat Aug 28, 2004 12:25 am

Post by bob_the _builder »

That is what I wanted.. Its the same as when it was calling records from db.

The problem is accessing the data from the array again from the session ItemID

Thanks
User avatar
Stryks
Forum Regular
Posts: 746
Joined: Wed Jan 14, 2004 5:06 pm

Post by Stryks »

The array you make on page 1 is not accessible on page 2. The run-time of your code is right up until the page is done loading. After that, all local variables and code are flushed. The subsequent page has no knowledge of the array you set on the previous page.

So, you need to either carry the data across, by setting something like $_SESSION('items') = $items, or if your intent is to replace the database with a fixed list, then put the array creation into a separate file and include it when you need to pull back the info.

Both of these options feel wrong somehow ... it screams 'database ... database'.

But yeah ... if you do either option, you can get the info with something like ...

Code: Select all

$itemInfo = $items[$ItemId];
print_r($itemInfo);
Hope this helps
Post Reply