Reputation: 195
Everytime I click add cart button I pass an id value and get data from a database and I want to save it a session array.
<?php session_start() ?>
<?php require 'config.php' ?>
<?php
if (isset($_POST['id'])) {
$sql = "SELECT product_name, product_price FROM products WHERE id=".$_POST['id'];
$result = $mysqli->query($sql) or die($mysqli->error);
$result = $result->fetch_assoc();
if (isset($_SESSION['cart'])) {
if (isset($_SESSION['cart']['id'])) {
unset($_SESSION['cart']['id']);
}
}
$_SESSION['cart']['id'] = $result;
$cart = count($_SESSION['cart']);
//$cart = json_encode($_SESSION['cart']['id']);
echo $cart;
}
?>
Upvotes: 1
Views: 936
Reputation: 1569
Try something like this :
if(!isset($_SESSION['cart']))
$_SESSION['cart'] = array();//Declaration of the cart
$_SESSION['cart'][] = $result;//To add the result in cart
Upvotes: 1