Jump to content

PHP - Session isnt passing variables correctly.


lollipop2468

Recommended Posts

For some reason my session variable isn't been populated with my items as they are being passed? Can anyone point me in the direction why?

 

It will add an item into the array, however it will only display one at a time on the cart page. Meaning if I add one item A and then add an item B, item B will only be shown on the cart page.

 

This is just a test i'm playing with to help understand php a little more - obviously I need more practice!

 

Product Page

 

<?php
$result = mysql_query ('SELECT * FROM stock WHERE item="redplate"');
// fetch the resulting row as an associative array
while ($row = mysql_fetch_assoc ($result)){
  echo '£', number_format( $row ['price'] / 100, 2, '.', ' ' );
  }
?>
<form id="form1" name="form1" method="post" action="cart.php">
<input type="hidden" name="item" id="item" value="redplate" />
<input type="submit" name="button" id="button" value="Add to Shopping Cart" />

 

Shopping Cart Page

 

<?php session_start(); 
?>
<?php include 'dbconfig.php'//connects to database?>
<?php include 'connect.php'//checks my credentials?>
<?php
////Adding something to the shopping basket from product page
if (isset($_POST['item'])){
    $item = $_POST['item'];
    $wasFound = false;
    $i = 0; 
    //If cart is not set or cart array empty
    if (!isset($_SESSION['cart_array'])||count($_SESSION['cart_array']) < 1) {
    //Run if the cart is empty or not set
    $_SESSION['cart_array'] = array(1 => array('item' => $item, 'quantity' => 1));
    }else{
    //Run if the cart has at least one item
     foreach ($_SESSION['cart_array'] as $each_item) {
     $i++;
     while (list($key, $value) = each($each_item)) {
        if ($key == 'item' && $value == $item) {
        //This item is already in our shopping cart so add one to quantity
        array_splice($_SESSION['cart_array'], $i-1, 1, array(array('item' => $item, 'quantity' => $each_item['quantity']+1)));
        $wasFound = true;
     } //Close if condition
} //Close While loop
}//Close foreach loop
//
if ($wasFound == false) {
array_push($_SESSION['cart_array'],array('item' => $item, 'quantity' => 1));
}
}
}   
?>
<?php
//////If a user empties their cart
if (isset($_GET['cmd'])&& $_GET['cmd']=="emptycart")
    {
    unset($_SESSION["cart_array"]);
    }
/////This will empty their cart and reset array
?>

<?php
///// Puts cart together for shopper to view
$cartOutput="";
if (!isset($_SESSION['cart_array'])|| count($_SESSION['cart_array'])<1){
$cartOutput = "<h2 align='center'>Your shopping basket is empty</h2>";
} else {
    $i = 0;
    foreach ($_SESSION['cart_array'] as $each_item){
    $i++;
    $item_name = $each_item['item'];
    $sql = "SELECT * from stock WHERE item = '$item'";
    $result = mysql_query($sql) or die(mysql_error());
    while ($row = mysql_fetch_array($result)){
    $product_name=$row['name'];
    $price=$row['price'];
    }
    $cartOutput = "<h2>Your Shopping Basket $i</h2>";
    $cartOutput = "Item Name: " .$each_item['item']. "<br />";
    $cartOutput = "Item Quantity: ". $each_item['quantity']. "<br />";

    //while (list($item, $price) = each($each_item)){
    //$cartOutput = "$key: $value<br />";
    //  }
    }
}
?>
//If user chooses to empty their shopping cart)
<?php 
if (isset($_GET['cmd']) && $_GET['cmd'] == "emptycart") 
{
    unset($_SESSION["cart_array"]);
}
?>

<a href="cartaction.php?cmd=emptycart">Click Here to Empty Your Shopping Cart</a>

Link to comment
Share on other sites

As far as I can tell what you had will work fine.  There was issues with your includes at the top of the page.  My sample has all your "parts" on one page.  I left your queries in though they're not doing much at this point.  print_r($_SESSION['cart_array']); shows quantity being updated and when changing the product name, it's added to the cart as well.  I would personally make this thing different but what you have seems to work.

<?php 
session_start(); 
include('dbconfig.php');//connects to database
include('connect.php');//checks my credentials

//If user chooses to empty their shopping cart)
if (isset($_GET['cmd']) && $_GET['cmd'] == "emptycart"){
    unset($_SESSION["cart_array"]);
}

////Adding something to the shopping basket from product page
if (isset($_POST['item'])){
$item = $_POST['item'];
$wasFound = false;
$i = 0; 
//If cart is not set or cart array empty
if (!isset($_SESSION['cart_array'])||count($_SESSION['cart_array']) < 1) {
	//Run if the cart is empty or not set
	$_SESSION['cart_array'] = array(1 => array('item' => $item, 'quantity' => 1));
}else{
	//Run if the cart has at least one item
	foreach ($_SESSION['cart_array'] as $each_item) {
		$i++;
		while (list($key, $value) = each($each_item)) {
			if ($key == 'item' && $value == $item) {
				//This item is already in our shopping cart so add one to quantity
				array_splice($_SESSION['cart_array'], $i-1, 1, array(array('item' => $item, 'quantity' => $each_item['quantity']+1)));
				$wasFound = true;
			} //Close if condition
		} //Close While loop
	}//Close foreach loop
	//
	if ($wasFound == false) {
	array_push($_SESSION['cart_array'],array('item' => $item, 'quantity' => 1));
	}
}
}   
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=windows-1252" />
  <title>Shopping Cart</title>
</head>
<body>
<?php
/*
echo "<pre>"; 
print_r($_SESSION['cart_array']);
echo "</pre>";
*/
	///// Puts cart together for shopper to view
	$cartOutput="";
	if (!isset($_SESSION['cart_array'])|| count($_SESSION['cart_array'])<1){
		$cartOutput .= "<h2 align='center'>Your shopping basket is empty</h2>";
	} else {
	    $i = 0;
	    foreach ($_SESSION['cart_array'] as $each_item){
		    $i++;
		    $item_name = $each_item['item'];
		    $sql = "SELECT name,price FROM stock WHERE item = '$item'";
		    $result = mysql_query($sql) or die(mysql_error());
			    while ($row = mysql_fetch_array($result)){
				    $product_name=$row['name'];
				    $price=$row['price'];
			    }  
		    $cartOutput .= "<h2>Your Shopping Basket $i</h2>";
		    $cartOutput .= "Item Name: " .$each_item['item']. "<br />";
		    $cartOutput .= "Item Quantity: ". $each_item['quantity']. "<br />";
	    }
	} 
	echo "$cartOutput";
?>

<a href="cart.php?cmd=emptycart">Click Here to Empty Your Shopping Cart</a>

<?php	
$result = mysql_query ('SELECT * FROM stock WHERE item="redplate"');
// fetch the resulting row as an associative array
while ($row = mysql_fetch_assoc ($result)){
  echo '£', number_format( $row ['price'] / 100, 2, '.', ' ' );
  }	
?>
	<form id="form1" name="form1" method="post" action="cart.php">
		<input type="hidden" name="item" id="item" value="Blueplate" />
		<input type="submit" name="button" id="button" value="Add to Shopping Cart" />
	</form>
</body>
</html>

Link to comment
Share on other sites

Looking at you original code your seriously confusing yourself. One thing has already been pointed out to you but just to reiterate that point: if you use the following code you will be reassigning your 1 key in your cart to whatever the new item is. You will not be creating new entries.

 

$_SESSION['cart_array'] = array(1 => array('item' => $item, 'quantity' => 1));

 

To create a new entry into an array you must use what Drummin suggested:

 

$_SESSION['cart_array'][] = array('item' => $item, 'quantity' => 1);

 

This will increment your car_array array key by 1 for each new entry.

 

Furthermore, you are repeatedly opening and closing the PHP output buffer by opening and closing PHP tags. This could, in large scripts, cause slow execution and is very bad practice. The first four lines in your "shopping cart" page should all be within a single <?php tag.

 

Regarding your actual logic I think its in a bit of a tangle. Break down the steps and worry about the actual programming later.

 

Steps

[*]Test if an item has been submitted.

[*]Determine if the item already exists in the cart.

[*]If already exists: increment item quantity by 1 or the value specified depending on how your system functions.

[*]Else: Add item to cart with a quantity value of 1.

[*]Then display a success message [Optional]

 

Your sort of already doing this but in a rather muddle. So lets break each step down individually

 

Test if an item has been submitted.

Simple enough so we wont bother going over it.

 

Determine if the item already exists in the cart.

Perhaps create a function for this along the lines of

 



function cartItemExists($newItem){
    foreach($_SESSION['cart'] as $key=>$item){
        if(key($item) == $newItem) return $key;
    }

    return false;
}

 

Use this in a simple if statement and you can move on to the next step. Notice if the item already exists it will return an array key which can be used to increment the cart item as your SESSION['cart'] looks something like:

 



array(cart => array(
    1 => array(item=>value)
    2 => array(item=>value)
    3 => array(item=>value)
)

 

So you must know which value, 1, 2 or 3, you need to use to get the item.

 

I'm going to assume you can continue from here and write the logic for the next few steps. Just for the record, you can combine all of this into a single function or putting it directly into your script but I wanted to break it down for you so you understand how to construct your script in the future. Please note I also used a slightly different array structure to the one you were using as it made more sense to me to use the array key as the item name and the value as the quantity. You can do whatever you want, neither is correct nor wrong.

 

Good attempt though.

Link to comment
Share on other sites

Thank you for your help - I really appriciate it!!

 

Ive have included the changes you suggested (Drummin) - however the item still isn't being passed which I think is causing nothing to show.

 

Something is going through as this is in the array print out:

 

Array
(
    [0] => Array
        (
            [item] => 
            [quantity] => 1
        )

    [1] => Array
        (
            [item_id] => 
            [quantity] => 3
        )

)

 

It seems as if its not passing the 'redplate' from the product page into the cart page for it to query it and get its details out?

 

CPD - Thank you so much for taking the time to help me out too! Im a newbie to this so trying to take little steps - just ending up in a muddle!

Link to comment
Share on other sites

I've no idea how you've managed to generate two different array keys: "item" and "item_id".

 

If your script isn't assigning the item id or item name (not entirely sure from that array which your trying to use) then its likely the "item" variable isn't actually being set properly.

 

Ensure all your data is being correctly posted to the header and all your form names match up correctly with whatever your trying to access in the $_POST variable.

 

It may just be a simple typo.

 

You also need to review the code which sets a new item and which increases the quantity by 1 to ensure all the array keys match up which is what I referred to in my first sentence.

Link to comment
Share on other sites

Thanks CPD - turn out in the array I was mentioning item_id and item. Corrected that now and its updating fine!

 

On the cart page I use:

 

if (isset($_POST['pid'])){
$item = $_POST['pid'];
$wasFound = false;
$i = 0; 

 

Which accepts the 'pid' from the add to cart button on the product page here:

 

		<form id="form1" name="form1" method="POST" action="cart.php">
        <input type="hidden" name="pid" id="pid" value="blueplate" />
        <input type="submit" name="button" id="button" value="Add to Shopping Cart" />
      	</form>

 

Should I be doing anything else or should this work and ive just gone wrong somewhere!

Link to comment
Share on other sites

Print out your $item variable and see what it contains (do it directly after you set it) if it comes out correctly its to do with whatever code comes after that. If not than its something to do with posting your data to the header or the way your retrieving it.

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.