[Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 523
  • Last Modified:

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

0
FairyBusiness
Asked:
FairyBusiness
  • 18
  • 7
  • 5
  • +3
4 Solutions
 
Aaron TomoskyTechnology ConsultantCommented:
I don't think you need arraypush. To set it:
$items[$item]=$qty

Then retrieve it in reverse:
$qty = $items[$item]
0
 
FairyBusinessAuthor Commented:
I am trying to retrieve it outside the function so i'm not sure how to do this. ..  set $items as a global??
0
 
FairyBusinessAuthor Commented:
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.
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
Aaron TomoskyTechnology ConsultantCommented:
Do Var_dump($items) whenever to see what's there
0
 
FairyBusinessAuthor Commented:
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.
0
 
Aaron TomoskyTechnology ConsultantCommented:
I can't look through it very well from my phone but I'm sure ray or someone will be along soon.
0
 
FairyBusinessAuthor Commented:
Hopefully lol

This really sucks because I got the other session values for the shopping cart to work. . .
0
 
Lukasz ChmielewskiCommented:
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 ?
0
 
dnzone88Commented:
Try using the following function. See if it help. The function below assume the following:
1. if $_POST['qty'] is set to 0 it will remove the item store in the session
2. if $_POST['qty'] is greater than 0 it will store the qty into the session
3. if the item is store in the session it will return the qty from the session else it will return 0
function get_qty($item) {
	if(isset($_POST['submit']) && empty($errors)) { // Form has been submitted
		$qty = trim(mysql_clean_strings($_POST['qty']));
		
		if($qty > 0){
			// check if sesstion exist
			if(!isset($_SESSION['items'])) {
				$_SESSION['items'] = array();
			}
			
			// store the new qty into the session for the item
			$_SESSION['items'][$item]=$qty;
		}
		else{
			if(isset($_SESSION['items'][$item])){
				// remove the item from the session
				unset($_SESSION['items'][$item]);
				
				// if no item in the session remove the session
				if(count($_SESSION['items'])==0){
					unset($_SESSION['items']);
				}
			}
		}
	}
	
	// check if session exist
	if(isset($_SESSION['items'][$item])){
		// retrieve previously stored qty
		$qty = $_SESSION['items'][$item];
	}
	else{
		$qty = 0;
	}
	
	return $qty;
}

Open in new window

0
 
Ray PaseurCommented:
To add a "sub-array" element to the end of the array, you just use empty brackets like this:

$_SESSION["items"][] = array( $item => $qty );
0
 
Ray PaseurCommented:
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);
}
0
 
FairyBusinessAuthor Commented:
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);
0
 
Ray PaseurCommented:
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!
0
 
FairyBusinessAuthor Commented:
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!)
0
 
Ray PaseurCommented:
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;
0
 
Ray PaseurCommented:
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
0
 
FairyBusinessAuthor Commented:
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)  ??????????
0
 
dnzone88Commented:
on your http://auroriella.com/bracelet.php?item=b3, your $_POST request is empty so the function get_qty() will return 0 quantity.
	if(isset($_POST['details']) && !empty($item)) { // $_POST['details'] is not set so cannot go into the if statement
		$qty = trim(mysql_clean_strings($_POST['qty']));

Open in new window

There is no $_POST['details'] and $_POST['qty'] request, that's why your item never get registered in the session.

For testing purposes can you change your code
$item = get_item();
get_qty($item);

Open in new window

to
$item = get_item();
$_POST['details']=1;
$_POST['qty']=5;
echo 'quantity for ', $item, ' is ', get_qty($item), '<br />';

Open in new window

to see if the session variable is registered or not after you add the $_POST request
0
 
FairyBusinessAuthor Commented:
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
0
 
dnzone88Commented:
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;
0
 
FairyBusinessAuthor Commented:
ok done
0
 
dnzone88Commented:
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.  
0
 
FairyBusinessAuthor Commented:
Whenever I click submit the item variable disappears
0
 
FairyBusinessAuthor Commented:
Whenever I click submit the item variable disappears
0
 
dnzone88Commented:
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.
0
 
FairyBusinessAuthor Commented:
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']));

0
 
dnzone88Commented:
there is a query Query failed message in your show_cart.php.

why do you need to add this statement in the get_qty function?
$item = trim(mysql_clean_strings($_POST['item']));

Open in new window

I think should be something like this
$item = isset($_POST['item']) ? $_POST['item'] : ''; // get the item choose by user
$qty = get_qty($item); // retrieve qty from the session

Open in new window

0
 
FairyBusinessAuthor Commented:
I cant put get_qty($item) in side its own function??
0
 
dnzone88Commented:
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.
0
 
FairyBusinessAuthor Commented:
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. . .
0
 
FairyBusinessAuthor Commented:
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

0
 
FairyBusinessAuthor Commented:
My here doc is not working. . . I narrowed it done to that
0
 
FairyBusinessAuthor Commented:
Oh I didn't echo it.  Ok, well everything is working finally with my shopping, yeah!!! hopefully no more problems!!
0
 
robertkennedyCommented:
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?
0
 
FairyBusinessAuthor Commented:
Ok new question but its not working exactly how I want it to BUT AT LEAST ITS THERE:

http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_26987016.html
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

  • 18
  • 7
  • 5
  • +3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now