Jump to content

Add number to session value


oMIKEo

Recommended Posts

Hi all,
 
I'm trying to build a simple shopping cart, there are only 8 products and I want to save the quantity value into a section for each product (product1, product2, etc).
 
I'm having a problem where the I can't get the session value to increase by one if the same item is added to the cart again.
 
Here is the code I have so far, am I missing something or is there a php setting that would cause this not to work.
 

<?php
session_start();

// setup

if(!isset($_SESSION['product1']))
$_SESSION['product1'] = 0;
if(!isset($_SESSION['product2']))
$_SESSION['product2'] = 0;
if(!isset($_SESSION['product3']))
$_SESSION['product3'] = 0;
if(!isset($_SESSION['product4']))
$_SESSION['product4'] = 0;
if(!isset($_SESSION['product5']))
$_SESSION['product5'] = 0;
if(!isset($_SESSION['product6']))
$_SESSION['product6'] = 0;
if(!isset($_SESSION['product7']))
$_SESSION['product7'] = 0;
if(!isset($_SESSION['product8']))
$_SESSION['product8'] = 0;


// add product 
if(mysql_escape_string($_GET['add']) != '') {
	$addItem = mysql_escape_string($_GET['add']);
	$_SESSION["product$addItem"] = $_SESSION["product$addItem"] + 1;
}
echo "product$addItem = ".$_SESSION["product$addItem"];


?>

 
Thanks!

Link to comment
https://forums.phpfreaks.com/topic/290293-add-number-to-session-value/
Share on other sites

This works for me:

<?php

session_start();

if(!isset($_SESSION['product1']))
$_SESSION['product1'] = 0;
$addItem = 1;

$_SESSION["product$addItem"] = $_SESSION["product$addItem"] + 1;

echo "product$addItem = ".$_SESSION["product$addItem"

Check $addItem and what value do you get. Your example is an example of bad codding design. 

All I get is the following even after refreshing a bunch of times:

product1 = 1

Ok, had a change of plan and uploaded the code to some other hosting and its working fine so I guess its a php session issue with that hosting causing the data to not actually save in the sessions. I'll contact support and see if they can figure it out for me.

 

Thanks for your help!

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.