how to store cart session for logged in user using php. i noticed that the same cart information is shown to all users when logged in, which is wrong. every user should have their own different cart information based on what they might have added up. how can i tie cart information to logged in users or each users.
add to cart php
if(isset($_GET['add'])){
$query = query("SELECT * FROM product WHERE product_id=" . escape_string($_GET['add']). " ");
confirm($query);
while($row = fetch_array($query)){
if($row['product_quantity'] !=$_SESSION['product_' . $_GET['add']]){
$_SESSION['product_' . $_GET['add']]+=1;
redirect("cart.php");
} else {
set_message("We have only" . $row['product_quantity'] . " " . "Available");
redirect("cart.php");
}
}
}
showing value in cart
$total = 0;
$item_quantity = 0;
foreach($_SESSION as $name =>$value){
if($value > 0){
if(substr($name, 0, 8) == "product_"){
$lenght = strlen($name) - 8;
$id = substr($name, 8 , $lenght);
$query = query("SELECT * FROM product WHERE product_id = " . escape_string($id) . " ");
confirm($query);
while($row= fetch_array($query)){
$sub = $row['product_price']*$value;
$item_quantity +=$value;
$product = <<<DELIMETER
<tr>
<td class="col-xs-1">
<img src="images/products/{$row['product_image']}" alt="" class="img-responsive">
</td>
<td class="col-xs-4 col-md-5">
<h4>
<a href="single-product.php">
{$row['product_title']}
</a>
<small>
M, Black, Esprit
</small>
</h4>
</td>
<td class="col-xs-2 text-center">
<span>
₹{$row['product_price']}
</span>
</td>
<td class="col-xs-2 col-md-1">
<a href="carts.php?remove={$row['product_id']}" class='btn btn-primary'>
<i class='fa fa-minus'></i>
</a>
<div class="form-group">
<input type="text" class="form-control" value="{$value}">
</div>
<a href="carts.php?add={$row['product_id']}" class='btn btn-primary'>
<i class='fa fa-plus'></i>
</a>
</td>
<td class="col-xs-2 text-center">
<span>
<b>
₹{$sub}
</b>
</span>
</td>
<td class="col-xs-1 text-center">
<a href="carts.php?delete={$row['product_id']}" class="btn btn-primary">
<i class="fa fa-times"></i>
</a>
</td>
</tr>
DELIMETER;
echo $product;
}
$_SESSION['item_total'] = $total += $sub;
$_SESSION['item_quantity'] = $item_quantity;
}
}
}
i have user session $_SESSION['user_email'] but unable to know that how to link with cart session for different user. I am beginner in php
I would create another session variable called "TOKEN" maybe do an MD5 hash of the current Unix timestamp and store it as the session token. Using an MD5 hash of the current Unix timestamp guarantees a unique session token every time. You would want this created when the user logs in and also store the current session token in the database in your user table. This way you can call the session variables where the token equals the users token. You could also go the route of creating cookies. Either way, they are both simple to do and effective.