Jump to content

[SOLVED] shopping cart array


seaweed

Recommended Posts

What's the best way to store shopping cart items in a session? Figure it has an sku, a color and a size... how would you store that in a session and then pull it back out to it can be dropped into the db once paid for?

Link to comment
Share on other sites

Okay, so a user clicks add to cart, I POST these to a script and put them into a session... how do I separate out multiple items... say they ordered this:

 

Qty 3  Medium Red Shirts, SKU #5001

Qty 2  Large Blue Shirts, SKU #5001

Qty 4  Large Green Pants (sexy), SKU #5005

Qty 1  Small Purple Hats (goes great with green pants), SKU #5007

 

 

Two of them have the same SKU, but they will be separate cart items, same sku but different size/color.

 

The plan is to have an "orders" table that has a unique orderID and userid...

And then an orderItems table with one row per item ordered, which also has the same unique orderID

so to view the order it queries all orders where orderID = $orderID... I got that down. The user table has all their shipping info, connected with userid.

 

Forget all that for a minute.

 

Before they finalize the order, while it is still in the session, how do I store them? Not how to use $_SESSION but what variables to use? Can I create this with a session?

 

$_SESSION['item1'] = array(SKU5001,Large,Blue,Qty3);

$_SESSION['item2'] = array(SKU5005,Medium,Green,Qty4);

 

etc...

 

If it were just SKU numbers I would build a comma delimited string and use explode, but it has three variables: SKU, size, color...

Link to comment
Share on other sites

The best way to do this is use an associative array like this:

 


$_SESSION['CART']['ITEMS'][] = array(
   'product_id' => $product_id,
   'product_name' => $product_name,
   'color' => $color
);

 

You could then access your cart items easily, for example loop through them:

 

foreach($_SESSION['CART']['ITEMS'] as $item)
{
    echo "product_name: " . $item['product_name'];
    echo "color: " . $item['color'];
}

Link to comment
Share on other sites

Okay, perfect. I tested it and it works: (I know, I need to sanitize my input)...

 

<?php

session_start();
if (! $_SESSION[active]) {
      $_SESSION[active] = 1;
}

$id = $_POST['id'];
$qty = $_POST['qty'];
$size = $_POST['size'];
$color = $_POST['color']; 

$_SESSION['CART']['ITEMS'][] = array(
   'product_id' => $id,
   'product_qty' => $qty,
   'product_size' => $size,
   'product_color' => $color
);

header("Location: shoppingcart.php");

?>

 

<?php

  foreach($_SESSION['CART']['ITEMS'] as $item)
{
    echo "product_id: " . $item['product_id'] . " ";
    echo "qty: " . $item['product_qty'] . " ";
    echo "size: " . $item['product_size'] . " ";
    echo "color: " . $item['product_color'] . " ";
    echo "<br /><br />";
}

?>

 

This outputs:

 

product_id: 31 qty: 21 size: Small color: Blue

 

product_id: 32 qty: 17 size: Medium color: Red

 

product_id: 33 qty: 5 size: Medium color: Blue

 

product_id: 34 qty: 7 size: X-Large color: White

 

 

So, I can place an SQL insert statement in the foreach loop to insert a new row

in my orderItems table for each product, correct? If it's that simple, I'm done!

Echoing the cart to the user is easy as pie.

 

 

 

Link to comment
Share on other sites

Few more quick questions...

 

1.  What's the best way to initiate the session for this application?

 

    Currently all of my pages use this in a header include file:

 

     session_start();
     if (! $_SESSION[active]) {
           $_SESSION[active] = 1;
     }

 

      I just creates the dummy variable $active. When you get the the addtocart.php script though, it

      doesn't have a header as there's no html, should I just use this same session check, or actually check

      for the array like this?

 

      if (!isset($_SESSION['CART']['ITEMS']) || (!is_array($_SESSION['CART']['ITEMS']))) {
                  $_SESSION['CART']['ITEMS'] = array();

 

      I'm not sure on the way to do this or syntax...

 

 

 

2.  What's the best way to check if the item already exists in the cart and increment it, or decrease it if they want to remove it or subtract one? Maybe use in_array()?

 

 

 

 

Link to comment
Share on other sites

1. Unless you need to do something with $_SESSION['active'], then you don't need to use it on your addtocart.php page. By the way, use quotes when referencing an array element unless the key is an integer, so use $_SESSION['active'] not $_SESSION[active]

 

2. A foreach loop will be fine.

 

//product id
$product_to_change = 3; //you would get this from somewhere, not hard code it

foreach($_SESSION['CART']['ITEMS'] as $cart_item_id => $item)
{
     if($item['product_id'] == $product_to_change)
     {
          //product exists! increment the quantity
         $_SESSION['CART']['ITEMS'][$cart_item_id]['product_qty']++;
         break;
     }
}

 

If you want to decrease the quantity, then check if the quantity of the item is 1, is so then use:

unset($_SESSION['CART']['ITEMS'][$cart_item_id]);

 

If the quantity of the item is greater than 1, then just use:

$_SESSION['CART']['ITEMS'][$cart_item_id]['product_qty']--;

Link to comment
Share on other sites

Okay here's what I have:

 

 

addtocart.php

 

$prod_id = $_POST['prod_id'];
$prod_qty = $_POST['prod_qty'];
$prod_size = $_POST['prod_size'];
$prod_color = $_POST['prod_color']; 

foreach($_SESSION['CART']['ITEMS'] as $cart_item_id => $item)
{
     if($item['prod_id'] == $prod_id)
     {
         $_SESSION['CART']['ITEMS'][$cart_item_id]['prod_qty']++;
         break;
     }

     else {
 $_SESSION['CART']['ITEMS'][] = array(
             'prod_id' => $prod_id,
     'prod_qty' => $prod_qty,
     'prod_size' => $prod_size,
     'prod_color' => $prod_color
     );
     }
}

header("Location: cart.php");
exit;

 

 

cart.php

 

foreach($_SESSION['CART']['ITEMS'] as $item)  
   {
       echo "
<div class=\"cartrow\">
<div class=\"cartrow_id\">$item[prod_id]</div>
<div class=\"cartrow_desc\">$item[prod_color] $item[prod_size]</div>
<div class=\"cartrow_qty\">$item[prod_qty]</div>
<div class=\"cartrow_price\">xxx</div>
<div class=\"cartrow_subtotal\">xxx</div>
<div class=\"cartrow_update\">+ / -</div>
</div>
";
  }

 

The error I get, assuming it's a logic problem with the array?

 

Warning: Invalid argument supplied for foreach() in cart.php on line 17

Link to comment
Share on other sites

<?php include ('header.php') ?>
  <div class="main">
    <?php include ('leftcol.php') ?>
    <div class="catbody">
  <div class="cart">
    <div class="cartheaderrow">
	  <div class="cartheaderrow_id">ID</div>
	  <div class="cartheaderrow_desc">Description</div>
	  <div class="cartheaderrow_qty">Qty</div>
	  <div class="cartheaderrow_price">Price</div>
	  <div class="cartheaderrow_subtotal">Subtotal</div>
	  <div class="cartheaderrow_update"></div>
	</div>

  <?php
      
   foreach($_SESSION['CART']['ITEMS'] as $item)
	{
            
      echo "
		   <div class=\"cartrow\">
			<div class=\"cartrow_id\">$item[prod_id]</div>
			<div class=\"cartrow_desc\">$item[prod_color] $item[prod_size]</div>
			<div class=\"cartrow_qty\">$item[prod_qty]</div>
			<div class=\"cartrow_price\">xxx</div>
			<div class=\"cartrow_subtotal\">xxx</div>
			<div class=\"cartrow_update\">+ / -</div>
		   </div>
		   ";
	}

  ?>

    </div>
    </div>
  </div>
    <?php include ('footer.php') ?>
  </div>
</BODY>
</HTML>

Link to comment
Share on other sites

The error is saying $_SESSION['CART']['ITEMS'] does not exist.

 

Is there any code in header.php or leftcol.php that could be unsetting that array, or killing the entire session? Have you used unset() anywhere?

 

Also.... this error will occur if you haven't actually created that array. You might need to put

if(isset($_SESSION['CART']) == false || isset($_SESSION['CART']['ITEMS'] == false)
{
    $_SESSION['CART']['ITEMS'] = array();
}

 

in your header.php just under session_start()

Link to comment
Share on other sites

That throws a parse error:

 

Parse error: syntax error, unexpected T_IS_EQUAL, expecting ',' or ')' in header.php on line 3

 

line 3 is:

 

if(isset($_SESSION['CART']) == false || isset($_SESSION['CART']['ITEMS'] == false)

 

I tried moving the parens around with no luck.

Link to comment
Share on other sites

I tried that too, befor eyou posted,  but I still get the error. It's weird...

 

The header is like this:

 


<?php
session_start();
if(isset($_SESSION['CART']) == false || isset($_SESSION['CART']['ITEMS'] == false))
{
    $_SESSION['CART']['ITEMS'] = array();
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>

Link to comment
Share on other sites

Okay, error fixed.

 

Now, it isn't echoing anything to the cart.

 

Here's the various parts:

 

header.php

 

<?php
session_start();
if(isset($_SESSION['CART']) == false || isset($_SESSION['CART']['ITEMS']) == false)
{
    $_SESSION['CART']['ITEMS'] = array();
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>

 

addtocart.php

 

<?php

session_start();
if(isset($_SESSION['CART']) == false || isset($_SESSION['CART']['ITEMS']) == false)
{
    $_SESSION['CART']['ITEMS'] = array();
}

// This data needs cleaned before it goes to SQL!!!!! //

$prod_id = $_POST['prod_id'];
$prod_qty = $_POST['prod_qty'];
$prod_size = $_POST['prod_size'];
$prod_color = $_POST['prod_color']; 

foreach($_SESSION['CART']['ITEMS'] as $cart_item_id => $item)
{
     if($item['prod_id'] == $prod_id)
     {
         $_SESSION['CART']['ITEMS'][$cart_item_id]['prod_qty']++;

     }

     else {
 $_SESSION['CART']['ITEMS'][] = array(
             'prod_id' => $prod_id,
     'prod_qty' => $prod_qty,
     'prod_size' => $prod_size,
     'prod_color' => $prod_color
     );
     }
}

header("Location: cart.php");
exit;
?>

 

 

cart.php

 

<?php include ('header.php') ?>
  <div class="main">
    <?php include ('leftcol.php') ?>
    <div class="catbody">
  <div class="cart">
    <div class="cartheaderrow">
	  <div class="cartheaderrow_id">ID</div>
	  <div class="cartheaderrow_desc">Description</div>
	  <div class="cartheaderrow_qty">Qty</div>
	  <div class="cartheaderrow_price">Price</div>
	  <div class="cartheaderrow_subtotal">Subtotal</div>
	  <div class="cartheaderrow_update"></div>
	</div>

  <?php
      
   foreach($_SESSION['CART']['ITEMS'] as $item)
	{
            
      echo "
		   <div class=\"cartrow\">
			<div class=\"cartrow_id\">$item[prod_id]</div>
			<div class=\"cartrow_desc\">$item[prod_color] $item[prod_size]</div>
			<div class=\"cartrow_qty\">$item[prod_qty]</div>
			<div class=\"cartrow_price\">xxx</div>
			<div class=\"cartrow_subtotal\">xxx</div>
			<div class=\"cartrow_update\">+ / -</div>
		   </div>
		   ";
	}

  ?>

    </div>
    </div>
  </div>
    <?php include ('footer.php') ?>
  </div>
</BODY>
</HTML>

Link to comment
Share on other sites

You can't have the code like that on the addtocart.php page. What it's saying is foreach item in the cart, if the product id matches, increment, but if not add it. The interpreter is not getting inside the foreach() because the cart is empty.

 

Try this for your addtocart.php

 

$prod_id = $_POST['prod_id'];
$prod_qty = $_POST['prod_qty'];
$prod_size = $_POST['prod_size'];
$prod_color = $_POST['prod_color']; 

$found = false;
foreach($_SESSION['CART']['ITEMS'] as $cart_item_id => $item)
{
     if($item['prod_id'] == $prod_id)
     {
         $_SESSION['CART']['ITEMS'][$cart_item_id]['prod_qty']++;
	$found = true;
	break;
     }
}

if(!$found)
{
$_SESSION['CART']['ITEMS'][] = array(
	'prod_id' => $prod_id,
        'prod_qty' => $prod_qty,
        'prod_size' => $prod_size,
        'prod_color' => $prod_color
    );
}

 

Obviously that is not all of adtocart.php, you need to retain your code before and after that section.

Link to comment
Share on other sites

BTW, whenever I sit down to start a new project, I ALWAYS start by jamming to some old Blink 182 tunes, stuff from Dude ranch or Cheshire cat, it reminds me of the dotcom era when we all had jobs! Every time I get started, I open up Aliens Exist or Dammit and get in the mood.  ;D

Link to comment
Share on other sites

Here's what I ended up with for the updatecart script, it works flawlessly so far. Do you see anything wrong that I'm missing? I need to account for items w/o a color or size etc. still, I can see that. It's got more nests than a birdhouse but it works great - think/hope/pray!

 

<?php

session_start();
if(isset($_SESSION['CART']) == false || isset($_SESSION['CART']['ITEMS']) == false)
{
    $_SESSION['CART']['ITEMS'] = array();
}


  $do = $_POST['do']; // this is like add, subtract or remove
  $prod_id = $_POST['prod_id'];
  $prod_color = $_POST['prod_color'];
  $prod_size = $_POST['prod_size'];

  if (($prod_id == "") || ($prod_id == "0") || ($prod_id == NULL))
  {
echo "prod_id left blank"; // this verbiage is just for development, I'll change it later
  }
  elseif (is_numeric($prod_id) == false) 
  {
    echo "is_numeric failed on prod_id";  // this verbiage is just for development, I'll change it later
  }
  else {
  $found = false;
      foreach($_SESSION['CART']['ITEMS'] as $cart_item_id => $item)  {
        if(($item['prod_id'] == $prod_id) && ($item['prod_color'] == $prod_color) && ($item['prod_size'] == $prod_size)) {
      switch ($do) {
	    case "add":
                      $_SESSION['CART']['ITEMS'][$cart_item_id]['prod_qty']++;
	      $found = true;
	      break;

	    case "sub":
	        if($_SESSION['CART']['ITEMS'][$cart_item_id]['prod_qty'] <= 1) {
		  unset($_SESSION['CART']['ITEMS'][$cart_item_id]);
		  $found = true;
		  break;
	        }
	        else {
	          $_SESSION['CART']['ITEMS'][$cart_item_id]['prod_qty']--;
		  $found = true;
	          break;
                        } // closes inner else

	    case "rem":
	        unset($_SESSION['CART']['ITEMS'][$cart_item_id]);
	        $found = true;
	        break;

	     } // closes switch

                     $found = true;
	} // Closes if
    } // closes foreach
  } // closes outter else

header("Location: cart.php");
exit;
?>

?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.