Jump to content

Add number to session value


Go to solution Solved by jazzman1,

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

  • Solution

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. 

Edited by jazzman1

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!

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

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