Jump to content

update items in session


ragrim

Recommended Posts

Hi,

 

i have had some help from these forums building a shopping cart system and i can add items to cart, empty cart but i need some help on how to update quantities.

 

Here is the code i use to add items

 

$pid = $_POST['prodid'];
$q = $_POST['qty'];

if(array_key_exists($pid, $_SESSION['cart']))
{
	$_SESSION['cart'][$pid]=$_SESSION['cart'][$pid]+$q;	
}
ELSE
{
	$_SESSION['cart'][$pid]=$q;
}

 

Im displaying my items in a table with a text field for quantities which can be changed then click update. i see there is 2 things i need to do, first is to somehow create a loop for all the items in my table, i have no clue where to start on that, and then in that loop i have my update command.

 

im assuming the code to update would be something like

 

$_SESSION['cart'][$pid]=$_SESSION['cart'][$pid][$qty]	

 

where $qty is the value of the text box in my table.

 

Any help would be appreciated.

Link to comment
https://forums.phpfreaks.com/topic/252489-update-items-in-session/
Share on other sites

update, after i posted i had a lightbulb moment and figured out how i can do the update, but now my problem is how can i pass the values of the new quantities to the script, for example here is my form and how i display the quantities.

 

<td><input type='text' value='" . $value . "'</td>

 

Now after this has processed and i have say 3 items in cart it looks like this in html

 

<td><input type='text' value='1'</td>
<td><input type='text' value='2'</td>
<td><input type='text' value='3'</td>

 

because each text field doesnt have a unique name how can i pass each of the values to my script to check if the qty has changed and if needed update the quantities.

 

Cheers.

  Quote

because each text field doesnt have a unique name how can i pass each of the values to my script to check if the qty has changed and if needed update the quantities.

 

You give them unique names with which you can tie that box back to a particular cart item.  The easiest way to manage that is to give them a name which will generate an array and use some id as the key, such as the product id:

foreach  ($_SESSION['cart'] as $productId=>$qty){ 
   echo '<input type="text" name="quantities['.$productId.']" value="'.$qty.'">';
}

 

Then on the receiving end:

foreach ($_POST['quantities'] as $productId=>$qty){
   $_SESSION['cart'][$productId] = intval($qty);
}

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.