Link to home
Start Free TrialLog in
Avatar of FairyBusiness
FairyBusinessFlag for United States of America

asked on

How to use array_push when you are initializing the array with a key?

Hi, I am trying to retrieve the quantity for the specific product selected.  I want the qty to go with the product so I make the product ($item) the key and $qty the value.  Only I dont know how to use array_push with it.  I am using this because I want the function to store all of the $item/$qty it receives.  Anyone know how to do this??

function get_qty($item) {
	if(isset($_POST['submit']) && empty($errors)) { // Form has been submitted
		$qty = trim(mysql_clean_strings($_POST['qty']));
		if(!isset($_SESSION['items'])) {
			$_SESSION['items'] = array(
				$item => $qty
			);
		}
	array_push($_SESSION['items'], $item => $qty);
	$quantity = $_SESSION['items'];
	}
	else {
		$qty = $quantity[$item];
		return $qty;
	}
}

Open in new window

Avatar of Aaron Tomosky
Aaron Tomosky
Flag of United States of America image

I don't think you need arraypush. To set it:
$items[$item]=$qty

Then retrieve it in reverse:
$qty = $items[$item]
Avatar of FairyBusiness

ASKER

I am trying to retrieve it outside the function so i'm not sure how to do this. ..  set $items as a global??
Ok, well its kind of working:

function get_qty($item) {
	if(isset($_POST['submit']) && empty($errors)) { // Form has been submitted
		$qty = trim(mysql_clean_strings($_POST['qty']));
		if(!isset($_SESSION['items'])) {
			$_SESSION['items'] = array();
			$items = $_SESSION['items'];
			$items[$item] = $qty;
		}
		else {
			$items[$item] = $qty;
		}
	$qty = $items[$item];
	return $qty;
	}
}

Open in new window


Problem is without the array_push I think its not storing old values, its just displaying the quantity of whatever was clicked last.  (overwriting)  The key/value/pair is not working either because its putting the last quantity selected with other products that I didn't give a new quantity to.
Do Var_dump($items) whenever to see what's there
ok, well I did this:

function get_qty($item) {
	if(isset($_POST['submit']) && empty($errors)) { // Form has been submitted
		$qty = trim(mysql_clean_strings($_POST['qty']));
		if(!isset($_SESSION['items'])) {
			$_SESSION['items'] = array();
		}
		$_SESSION['items'] = array(
			$item => $qty
		);
		array_push($_SESSION['items'], $item, $qty);
		$quantity = $_SESSION['items'];
		$qty = $quantity[$item];
		return $qty;
	}
}

Open in new window


It works when I select a product and immediately it re-directs me to my shopping cart, but once I leave it and come back to view it all the quantities are gone.  So its not storing them as session apparently. ..  can you see why?  Also, it gives all of the products in the shopping cart the last selected quantity when they do have a quantity.
I can't look through it very well from my phone but I'm sure ray or someone will be along soon.
Hopefully lol

This really sucks because I got the other session values for the shopping cart to work. . .
Are you trying to GET or SET the values to session ? The function takes only the $item parameter but you fire it when you post your form. In case you want to get the quantity of some item from a session you would not use the form that posts that quantity. If you want to set the quantity to a item tahe function should take two parameters: item, qty.

Am I thinking correct ?
ASKER CERTIFIED SOLUTION
Avatar of dnzone88
dnzone88
Flag of Malaysia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Then you will find that $_SESSION["items"] is an array of sub-arrays, each sub-array having  the key $item and the value $qty.  You can get to this information with something like this:

session_start();
foreach ($_SESSION["items"] as $sub_array)
{
    var_dump($sub_array);
}
Ok, well not sure why its not putting anything into the session.  (I hate sessions!!)

function get_qty($item) {
	var_dump($item);
	if(isset($_POST['details']) && !empty($item)) { // Form has been submitted
		$qty = trim(mysql_clean_strings($_POST['qty']));
		if($qty > 0){
			// check if sesstion exist
			if(!isset($_SESSION['cart'])) {
				$_SESSION['cart'] = array();
			}
			
			// store the new qty into the session for the item
			$_SESSION['cart'][$item]=$qty;
		}
		else{
			if(isset($_SESSION['cart'][$item])){
				// remove the item from the session
				unset($_SESSION['cart'][$item]);
				
				// if no item in the session remove the session
				if(count($_SESSION['cart'])==0){
					unset($_SESSION['cart']);
				}
			}
		}
	}
	
	// check if session exist
	if(isset($_SESSION['cart'][$item])){
		// retrieve previously stored qty
		$qty = $_SESSION['cart'][$item];
	}
	else{
		$qty = 0;
	}
	
	return $qty;
}

Open in new window


If you look on this page (its the one for testing):

http://auroriella.com/bracelet.php?item=b3

can you see that item is there because it dumps b3 as a string

but when you click 'add to bag'

http://auroriella.com/show_cart.php?action=add&table=bracelets&bag=b3

its null!!!

how can it not be passing the variable to the function when I call it like this on bracelet.php ???

$item = get_item();
get_qty($item);
There is no need to hate sessions, and they certainly do not hate you!  Here is everything you need to know to use sessions in PHP.

1. Use session_start() at the top of every page, unconditionally, every time, without fail, with no exceptions
2. Put data into the $_SESSION associative array with simple assignment statements like $_SESSION["cheese"] = "Cheddar";
3. Find data in the $_SESSION array with simple assignment statements like $cheese = $_SESSION["cheese"];
4. Expect the $_SESSION array to persist from one page to the next (unlike other variables which get re-initialized)

That is it - it is just that simple!
Can you think of any reason why my variable  $item is not getting passed from the bracelet page to the shopping cart page?  It never even makes it into the function!

function get_qty($item) {
      var_dump($item);


The var_dump returns null!

How can that be when the var_dump returns the item on the previous page??  And I called it too!!

get_qty($item);

(I can't even check the sessions yet because its not fulfilling the first parameter!)
Looking at the code above, I think you might want to add a bunch of echo statements into the function so you can follow the logic through step-by-step.  Also, it appears that the add-to-bag functionality may be a combined GET/POST method request.  That might be confusing and difficult to debug.

You can use var_dump() to print the contents of the session and post arrays - at this point in the development cycle you might want to add a page footer script that said something like this:

echo "<pre>";
echo "GET:";var_dump($_GET);
echo PHP_EOL;
echo "POST:"; var_dump($_POST);
echo PHP_EOL;
echo "SESSION:"; var_dump($_SESSION);
echo PHP_EOL;
echo "COOKIE:"; var_dump($_COOKIE);
echo PHP_EOL;
any reason why my variable  $item is not getting passed from the bracelet page to the shopping cart page?
It might be that the code depends on register_globals?  Not sure because we cannot see the code where you set the value of $item.  But read up on register_globals and make sure you are not using it.
http://php.net/manual/en/security.globals.php

You can use this simple test.

<?php // RAY_test_register_globals.php
echo $item;

Run it like this:
http://path/to/RAY_test_register_globals.php?item=Bracelet
Ok, I did:

http://auroriella.com/bracelet.php?item=b3

and its shows b3 as a $_GET and that my function for getting this is working:

function get_item() {
	if(isset($_GET['item']) && !empty($_GET['item'])) {
		$item = $_GET['item'];
		return $item;
	}
	elseif(isset($_GET['bag']) && !empty($_GET['bag'])) {
		$bag = $_GET['bag'];
		return $bag;
	}
}

Open in new window


So why doesn't it pass it to the function  get_qty($item)  ??????????
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Ok, I changed it to your code.  Details was just the name of the submit button.  I changed the name to submit so that it makes more sense now.

function get_qty($item) {
      var_dump($item);
      if(isset($_POST['submit']) && !empty($item)) { // Form has been submitted
if you change the the $_POST['details'] to $_POST['submit'] then you also need to change the testing code $_POST['details']=1; to $_POST['submit']=1;
ok done
so if you refresh your page you will see that b3 is registered in the session with the quantity of 5. That's mean the saving session part work. So your problem is the &_POST request part. You never pass the $_POST request into the bracelets.php page.  
Whenever I click submit the item variable disappears
Whenever I click submit the item variable disappears
Try create a hidden input and store your item's value in the hidden input on your bracelet.php. when you press the submit button the hidden input will also be post to the show_cart.php.
ok i did this:

<input type="hidden" name="item" value="<?php echo $item ?>" />

function get_qty($item) {
      var_dump($item);
      if(isset($_POST['submit']) && !empty($item)) { // Form has been submitted
            $item = trim(mysql_clean_strings($_POST['item']));
            $qty = trim(mysql_clean_strings($_POST['qty']));

SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I cant put get_qty($item) in side its own function??
you mean something like this?
function get_qty($item) {
    // your function code

   get_qty($item); // like this?

}

Open in new window

Yes you can, this is call a recursive function. But in your case I don't think you need to do that.
Item and qty are not the same thing.

So $qty = get_qty($item)  wont work

item is something like this: b3
and the qty is just a number from the selection box

also I dont think the problem is qty.  It seems to be making it to the shopping cart. Its the item that's not!  And its the item name that I use to pull the product from the database. . .
Ok, I got my session to work!!

for testing:  http://auroriella.com/bracelet.php?item=b3

Strangest thing now my table wont display!!

http://auroriella.com/show_cart.php

Why would my table not show??


function build_cart() {
if(!empty($_SESSION['cart'])){  
$cart = $_SESSION['cart'];
<<<HERE
<table border="1px" cellspacing="0" cellpadding="5px">
  <tr>
	<th>Item</th>
	<th>Price</th>
	<th>Quantity</th>
	<th>Total</th>
  </tr>
HERE;
	foreach($cart as $item => $qty) { 
		switch($item[0]) { // matches the first letter to a table
		  case 'b':
				$table = 'bracelets';
				echo "<tr>";
				echo "<td>" . cart_details($item, $table, $column='name') . "</td>";
				echo "<td>" . cart_details($item, $table, $column='price') . "</td>";
				echo "<td><input type=\"text\" name=\"qty\" value=\"" . $qty . "\" /></td>";
				echo "<td>" . cart_details($item, $table, $column='price') . "</td>";
				echo "</tr>";
				break;
		  case 'n':
				$table = 'necklaces';
				echo "<tr>";
				echo "<td>" . cart_details($item, $table, $column='name') . "</td>";
				echo "<td>" . cart_details($item, $table, $column='price') . "</td>";
				echo "<td>" . $qty . "</td>";
				echo "<td>" . cart_details($item, $table, $column='price') . "</td>";
				echo "</tr>";
				break;
		  case 'e':
				$table = 'earrings';
				echo "<tr>";
				echo "<td>" . cart_details($item, $table, $column='name') . "</td>";
				echo "<td>" . cart_details($item, $table, $column='price') . "</td>";
				echo "<td>" . $qty . "</td>";
				echo "<td>" . cart_details($item, $table, $column='price') . "</td>";
				echo "</tr>";
				break;
			}
		echo "</table>";
		}
	}
	else {
		echo "You have nothing in your shopping cart currently.";
	}
}

Open in new window

My here doc is not working. . . I narrowed it done to that
Oh I didn't echo it.  Ok, well everything is working finally with my shopping, yeah!!! hopefully no more problems!!
I dont think the issue is with the table not showing but it is actually with the products not being added to the 'bag' correctly when clicking the 'ADD TO BAG' button on the product page.

Are you able to provide the full code for the show_cart.php file?
Ok new question but its not working exactly how I want it to BUT AT LEAST ITS THERE:

https://www.experts-exchange.com/questions/26987016/Help-with-my-shopping-cart.html