Counting quality of item from a session array. semi working

Hi all,

i am working on a shopping system with an array integration but when i want to display the items in my cart,

it displays all items that are the same many times ive tried using an if and else statement but seems to not be working well semi working it just displays 1 of each item but not sure what i am doing wrong,

ive tried to print out the array using this

[PHP
print_r($_session[‘cart’]);



and this is the result

Array ( [0] => 0 [1] => 0 [2] => 0 [3] => 0 [4] => 0 [5] => 0 [6] => 0 [7] => 0 [8] => 0 [9] => 0 [10] => 0 [11] => 0 [12] => 0 [13] => 0 [14] => 0 [15] => 0 [16] => 0 [17] => 0 [18] => 0 [19] => 0 [20] => 0 [21] => 0 [22] => 6 [23] => 6 [24] => 6 [25] => 6 [26] => 6 [27] => 6 [28] => 6 [29] => 6 [30] => 6 [31] => 6 [32] => 6 [33] => 6 [34] => 6 ) 

Now this is my php code


```php

include("dbconnect.php");
	$cQuery="SELECT * FROM shop";
	$result=mysqli_query($con,$cQuery);;
	if(!$result)
	{
		echo "Error:".mysqli_error($con);
	}
	else
	{
		$count=$result->num_rows;
		if($count>0)
		{
			while($data=$result->fetch_assoc())
			{
				$items[]=$data['name'];
				$prices[]=$data['cost'];
				$str[]=$data['str'];
			}
		}
		else
		{
			echo "No Items in ShOP";
		}
	}
	//
	$total = 0; // add up the total
	// list the quantities in the cart rather than the catalog
	?>
	<table>
    <tr>
    	<th>Item:</th>
        <th>Price:</th>
        <th>Quanty:</th>
    </tr>
	<?
	for ($i = 0; $i < count($_SESSION['cart']); $i++)
	{
	   print_r($_SESSION['cart']);
	   if($e>=2)
	   {
			//
			echo '<tr>
			<th>'.$items[$_SESSION['cart'][$i]].'</th>
			<th>$'.$prices[$_SESSION['cart'][$i]].'</th>';
			//echo '<th>'.count($items[$_SESSION['cart'][$i]]).'</th></tr>';
			//
			
	   }
	   else if($e<2)
	   {
		   
		   echo '<tr>
			<th>'.$items[$_SESSION['cart'][$i]].'</th>
			<th>$'.$prices[$_SESSION['cart'][$i]].'</th>';
			echo '<th>e1</th></tr>';
	   }
		$total += $prices[$_SESSION['cart'][$i]];
	}?>
		<tr>
        	<th>Total</th>
            <th>$<?php echo number_format($total, 2); ?></th>
        </tr>
    </table>
	<?

The abov code is displaying the following

broken stick $100 e1
broken stick $100 e1
broken stick $100 e1
broken stick $100 e1
broken stick $100 e1
broken stick $100 e1
broken stick $100 e1
broken stick $100 e1
broken stick $100 e1
broken stick $100 e1
broken stick $100 e1
broken stick $100 e1
broken stick $100 e1
broken stick $100 e1
broken stick $100 e1
broken stick $100 e1
broken stick $100 e1
broken stick $100 e1
broken stick $100 e1
broken stick $100 e1
broken stick $100 e1
broken stick $100 e1
Stead $50,000 e1
Stead $50,000 e1
Stead $50,000 e1
Stead $50,000 e1
Stead $50,000 e1
Stead $50,000 e1
Stead $50,000 e1
Stead $50,000 e1
Stead $50,000 e1
Stead $50,000 e1
Stead $50,000 e1
Stead $50,000 e1
Stead $50,000 e1
Stead $50,000 e1
Stead $50,000 e1

Why is it doing that should display this

Stead x 16
Broken Stick x 22

What am i doing wrong??

The problem is not when you pull them out it’s how you are putting them into the session (or object) as they add products to their cart.

Post the code where you add the new items in if you could.

I’ll also see if I can dig up one of my cart objects to show you how it can be done without these type problems

Here’s some objects I just used on a cart I built, don’t know if it is too advanced but here you go:

Item object:

<?php

class Item 	{

	private $product_id;
	private $quantity;
	private $is_bulk_pricing;
	private $special_attributes; // an array of attributes or nothing
	private $item_price;

	function fill_item($product_id, $quantity, $is_bulk_pricing, $special_attributes, $item_price)	{	
		$this->product_id = $product_id;
		$this->special_attributes = $special_attributes;
		$this->quantity = $quantity;
		$this->is_bulk_pricing = $is_bulk_pricing;
		}

	function get_product_id()	 {	
		return $this->product_id;	
		}

	function set_quantity($quantity)	{	
		$this->quantity = $quantity;	
		}

	function update_quantity($added)	{
		$this->quantity += $added;
		}

	function get_quantity()	{	
		return $this->quantity;	
		}

	function get_is_bulk_pricing()	{
		return $this->is_bulk_pricing;
		}

	function set_special_attributes($special_attributes)	{
		$this->special_attributes = $special_attributes;
		}

	function get_special_attributes()	{
		return $this->special_attributes;
		}

}

And then the cart object:

<?php

class CartObject {

	var $cart_total;
	var $items = array(); // will be an array of Item objects
	var $customer;

	function add_item($product_id, $item)	{
		$this->items[$product_id] = $item;
		}

	function update_items($items)	{ 
		$this->items = $items;
		}

	function remove_item($product_id)	{
		unset($this->items[$product_id]);
		}
	
	function get_items()	 {
		return $this->items;
		}

	function is_item_in_cart($prod_id)	{
		return in_array($prod_id, array_keys($this->items));
		}

	function get_item_in_cart_quantity($prod_id)	{
		
		$item = $this->items[$prod_id];

		if ($item != NULL)	{
			return $item->get_quantity();
			}
		else	{
			return 0;
			}
		}

	function get_total_item_qty()	{
		
		$total = 0;

		foreach ($this->items as $id => $info)	{
			$total += $info->get_quantity();
			}

		return $total;
		}

	function set_customer($customer)	{
		$this->customer = $customer;
		}

	function get_customer()	{
		return $this->customer;
		}
}

Basically you want you items keyed with something like the product id and if that ID already exists in your object or array or session you want to only add to the quantity, not add another one.

okay how would i go about intergrating that into my system??

You mean my code or checking?

If you mean checking to see if the the item is already in your (assuming) session would be to test before adding it. I would assume you are using a product id so test on that.

In looking at your original code it appears you are only adding the product id to the session, then using that id to get your prices and product description, that’s not going to work.

You are going to need to either create an object (even as simple as an array) and store the product id and the current quantity in the session (might as well add the product name too). That’s the only way you are going to be able to ‘control’ these quantities.

Give me 1/2 hour and I will code up an example that will get you moving in the right direction.

Here you go, a super simple example of what I am talking about (was actually a bit difficult to do for me because I am so used to do these things in objects)

copy and paste this into a PHP file called test.php, run it and play with it while studying what I’m doing … once you get that we can move deeper into it (although it may not be tonight)

<?php

	session_start();

	if ($_GET['clear'] == 'yes')	{
		unset($_SESSION['cart']);
		}

	if (isset($_SESSION['cart']))	{
		$cart = $_SESSION['cart'];
		}
	else	{
		$cart = array();
		}

	if (isset($_GET['p_id']))	{

		if (in_array($_GET['p_id'], array_keys($cart)))	{
			$cart[$_GET['p_id']]++;
			}
		else	{
			$cart[$_GET['p_id']] = 1;
			}
		
		}

	$_SESSION['cart'] = $cart;


	echo "<p>Your cart</p>\
";
	
	if (is_array($cart))	{
		foreach ($cart as $key => $value)	{
			echo "<p>product id: {$key} - quantity: {$value}</p>\
";
			}
		}

?>

<p><a href='test.php?p_id=123'>product 123 </a></p>
<p><a href='test.php?p_id=124'>product 124</a></p>
<p><a href='test.php?p_id=125'>product 125</a></p>
<p><a href='test.php?p_id=126'>product 126</a></p>

<p><a href='test.php?clear=yes'>clear cart</a></p>

Hi there, it works great only thing i want to add on to it now is the cost of each item and increase the cost of each item depend on how many quantiies the user wants,

now i cant seem to figure out how to do that here is my php ive made some small modiciations to it


if (isset($_GET['cost']))
	{
 		//
			if (in_array($_GET['cost'], array_keys($cart)))
			{
				$cart[$_GET['cost']]++;
			}
			else
			{
				$cart[$_GET['cost']] = 5.0;
			}
		//
    }
 
    $_SESSION['cart'] = $cart;
 
 
    echo "<p>Your cart</p>\
";
    
    if (is_array($cart))
	{
		//
		foreach ($cart as $pr => $val)
		{
			$cost=$val;
        }
		//
        foreach ($cart as $key => $value)
		{
			echo "<p>product id: {$key} - quantity: {$value} cost : $val";
        }
    }
 
?>
?> 
<p><a href='cart2.php?p_id=123&cost=5'>product 123 </a></p>
<p><a href='cart2.php?p_id=124&cost=8'>product 124</a></p>
<p><a href='cart2.php?p_id=125&cost=9'>product 125</a></p>
<p><a href='cart2.php?p_id=126&cost=10'>product 126</a></p><?PHP

Since those links have the $cost variable added on them i want the script or $_get[‘cost’] to by increased depending the price of each item and increase depending on how many items they add to their cart,

So any ideas on how i can do that ive tried to add in another for loop but it seems to add another product under the one i am selecting which is not what i am wanting to do,

So if anyone can help me or point me in any direction on how do achieve this it would be great,

Thanks,William

Let me modify the one I built for you last night to take it to the next level.

Give me an hour or two.

Boy that was a fast hour wasn’t it? :wink: (actually I didn’t have to do something I thought I was going to have to do.)

So anyways, here is a modified version of the script I wrote last night, still keeping it as simple as possible. What you now do is create an array of arrays. The key in the main array ($cart) is the product id number, the value is an array that contains the quantity and the price per item.

Here’s the new code:

<?php

	session_start();

	if ($_GET['clear'] == 'yes')	{
		unset($_SESSION['cart']);
		}

	if (isset($_SESSION['cart']))	{
		$cart = $_SESSION['cart'];
		}
	else	{
		$cart = array();
		}

	if (isset($_GET['p_id']))	{

		if (in_array($_GET['p_id'], array_keys($cart)))	{
			
			$cart[$_GET['p_id']][0]++;
			
			}
		else	{
			
			$cart[$_GET['p_id']] = array(1, $_GET['price']);
			
			}
		
		}

	$_SESSION['cart'] = $cart;


	echo "<p>Your cart</p>\
";
	
	if (is_array($cart))	{

		foreach ($cart as $key => $value)	{
			echo "<p>product id: {$key} - quantity: {$value[0]}, total: $" . number_format($value[0] * $value[1], 2) . "</p>\
";
			}
		
		}

?>

<p><a href='test.php?p_id=123&price=5.00'>product 123 - price $5.00</a></p>
<p><a href='test.php?p_id=124&price=10.00'>product 124 - price $10.00</a></p>
<p><a href='test.php?p_id=125&price=7.50'>product 125 - price $7.50</a></p>
<p><a href='test.php?p_id=126&price=9.95'>product 126 - price $9.95</a></p>

<p><a href='test.php?clear=yes'>clear cart</a></p>

So now to access the quantity or the price you call $cart[product_id] and then the appropriate place in the inner array, so to get the quantity you call:

$cart[$_GET[‘p_id’]][0]

and then to get the item price (per item) you call:

$cart[$_GET[‘p_id’]][1]

So it is then simple to figure out your total for each ‘line item’ you mutliply

$cart[$_GET[‘p_id’]][0] * $cart[$_GET[‘p_id’]][1]

and of course to format the numbers correctly use the number_format function

You can also (as I have done in the loop that prints out the cart) use a foreach loop and then use $key => $value. $key is your product id, $value is your array with quantity and item price.

Get it?

If not feel free to post back with questions.

with that script above is there away for me to calculate the complete total of all items in the cart?? not just the the qaunty of each item

But of course there is … give me a second or two

OK here ya go.

Getting the cart total is as simple as adding up the ‘line items’ in the foreach loop:

$total += $value[0] * $value[1];

and then displaying the total where you want it, like this:

<?php
 
    session_start();
 
    if ($_GET['clear'] == 'yes')    {
        unset($_SESSION['cart']);
        }
 
    if (isset($_SESSION['cart']))   {
        $cart = $_SESSION['cart'];
        }
    else    {
        $cart = array();
        }
 
    if (isset($_GET['p_id']))   {
 
        if (in_array($_GET['p_id'], array_keys($cart))) {
            
            $cart[$_GET['p_id']][0]++;
            
            }
        else    {
            
            $cart[$_GET['p_id']] = array(1, $_GET['price']);
            
            }
        
        }
 
    $_SESSION['cart'] = $cart;
 
 
    echo "<p>Your cart</p>\
";
    
    if (is_array($cart))    {
 
        foreach ($cart as $key => $value)   {
            echo "<p>product id: {$key} - quantity: {$value[0]}, total: $" . number_format($value[0] * $value[1], 2) . "</p>\
";
			$total += $value[0] * $value[1];
            }

		echo "<p>Your total cart is: $" . number_format($total, 2) . "</p>\
";
        
        }
 
?>
 
<p><a href='test.php?p_id=123&price=5.00'>product 123 - price $5.00</a></p>
<p><a href='test.php?p_id=124&price=10.00'>product 124 - price $10.00</a></p>
<p><a href='test.php?p_id=125&price=7.50'>product 125 - price $7.50</a></p>
<p><a href='test.php?p_id=126&price=9.95'>product 126 - price $9.95</a></p>
 
<p><a href='test.php?clear=yes'>clear cart</a></p>

ive just taken a looked at that code why isnt it add the 2 numbers together? this is the result

Lookout Tower 2 $2,000,000
Invisibility Shield 3 $3,000,000
Total: $20,000,003,000,000.00

Should it be 5,000,000 not $20,000,003,000,000.00

Why did that occur??

Make sure you are using += for your math, NOT .= (which is concatenation)

and yes I typed it wrong in that post, edited now … my bad