I’m doing the following but it doesn’t work. it only has 1 item in the array no matter how many i add
can someone tell me what i’m doing wrong
session_start();
$pid = mysql_real_escape_string(trim($_GET["pid"]));
$price = mysql_real_escape_string(trim($_GET["price"]));
$quantity = mysql_real_escape_string(trim($_GET["quantity"]));
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = array();
$_SESSION['cart']['pid'] = $pid;
$_SESSION['cart']['total_price'] = $price;
$_SESSION['cart']['total_items'] = $quantity;
}else{
$_SESSION['cart']['pid'] = $pid;
$_SESSION['total_price'] += $price;
$_SESSION['total_items'] += $quantity;
}
It looks like you are just resetting the values in the array. Every time you set $_SESSION[‘cart’][‘pid’] you are re-writing over the last value. However, your total_price and total_quantity are probably incrementing correctly right?
Use
$_SESSION['cart']['pid'][] = $pid;instead. You need an array of ‘pid’ so that you can have multiple items. The [] operator tells php to treat the value as as array and push a new value onto the end of the array.EDIT: Your initialization under the
ifshould look like the following so that your [‘pid’] is an array of pid’s:Under the
elseyou would get:Note: You forgot [‘cart’] on the total_price and total_items under the
elseas was mentioned in other answers.