简体   繁体   中英

How can I add value in a session array every time I click add to cart button?

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;
  }
?>

Try something like this :

if(!isset($_SESSION['cart']))
    $_SESSION['cart'] = array();//Declaration of the cart
$_SESSION['cart'][] = $result;//To add the result in cart

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM