Store several values in the same instance of a PHP session

Asked

Viewed 443 times

2

Good morning, everyone,

I’m trying to create a shopping cart, and I’m racking my brain with what seemed to be something simple I’m learning now about programming languages, and I’m having trouble storing the sessions, the logic I used was the following

<?php

session_start();

//Pego o ID do produto passado pela URL

$id_prod = $_GET['id'];

//Se não existir a sessão carrinho, ele cria recebendo um array

if (isset($_SESSION['carrinho'])) {
    $_SESSION['carrinho'] = array();
}

//Essa parte ele deve criar a sessão carrinho com o ID que veio por GET, e armazenar 1 nele (Creio que esta parte tenha algo errado)

if (isset($_SESSION['carrinho'][$id_prod])) {
    $_SESSION['carrinho'][$id_prod] = 1;

//Caso já exista ele adiciona +1 ao valor existente
} else {
    $_SESSION['carrinho'][$id_prod] += 1;
}

/* Na hora de executar o var_dump, ele está substituindo o valor anterior pelo novo, queria que fosse um array com vários IDs de produtos e a quantidade de vezes que cada um foi adicionado ao carrinho */

var_dump($_SESSION['carrinho']);
?>

Personal thanks!

  • Could you give me an example of how you would like the session to go? From the description of what is happening it seems that the code is working normally.

  • Trying to detail better, I currently have "array(1) { [7]=> int(1) }", where 7 corresponds to the product id and int(1) corresponds to quantity.

  • What I need is "array(2) { [7]=> int(1) [8]=> int(1)}", I needed products 7 and 8 in the same array, but if I insert product 8, product 7 is deleted

  • After 3 hours of pure desperation and reading documentation I managed to solve the problem, was using isset in the 10° line, the correct was Empty

1 answer

2


Learn how to program using classes and objects. For example... Using this class:

<?php

class Cart
{
    /**
     * An unique ID for the cart.
     *
     * @var string
     */
    protected $cartId;
    /**
     * Maximum item allowed in the cart.
     *
     * @var int
     */
    protected $cartMaxItem = 0;
    /**
     * Maximum quantity of a item allowed in the cart.
     *
     * @var int
     */
    protected $itemMaxQuantity = 0;
    /**
     * Enable or disable cookie.
     *
     * @var bool
     */
    protected $useCookie = false;
    /**
     * A collection of cart items.
     *
     * @var array
     */
    private $items = [];
    /**
     * Initialize cart.
     *
     * @param array $options
     */
    public function __construct($options = [])
    {
        if (!session_id()) {
            session_start();
        }
        if (isset($options['cartMaxItem']) && preg_match('/^\d+$/', $options['cartMaxItem'])) {
            $this->cartMaxItem = $options['cartMaxItem'];
        }
        if (isset($options['itemMaxQuantity']) && preg_match('/^\d+$/', $options['itemMaxQuantity'])) {
            $this->itemMaxQuantity = $options['itemMaxQuantity'];
        }
        if (isset($options['useCookie']) && $options['useCookie']) {
            $this->useCookie = true;
        }
        $this->cartId = md5((isset($_SERVER['HTTP_HOST'])) ? $_SERVER['HTTP_HOST'] : 'SimpleCart') . '_cart';
        $this->read();
    }
    /**
     * Get items in  cart.
     *
     * @return array
     */
    public function getItems()
    {
        return $this->items;
    }
    /**
     * Check if the cart is empty.
     *
     * @return bool
     */
    public function isEmpty()
    {
        return empty(array_filter($this->items));
    }
    /**
     * Get the total of item in cart.
     *
     * @return int
     */
    public function getTotalItem()
    {
        $total = 0;
        foreach ($this->items as $items) {
            foreach ($items as $item) {
                ++$total;
            }
        }
        return $total;
    }
    /**
     * Get the total of item quantity in cart.
     *
     * @return int
     */
    public function getTotalQuantity()
    {
        $quantity = 0;
        foreach ($this->items as $items) {
            foreach ($items as $item) {
                $quantity += $item['quantity'];
            }
        }
        return $quantity;
    }
    /**
     * Get the sum of a attribute from cart.
     *
     * @param string $attribute
     *
     * @return int
     */
    public function getAttributeTotal($attribute = 'price')
    {
        $total = 0;
        foreach ($this->items as $items) {
            foreach ($items as $item) {
                if (isset($item['attributes'][$attribute])) {
                    $total += $item['attributes'][$attribute] * $item['quantity'];
                }
            }
        }
        return $total;
    }
    /**
     * Remove all items from cart.
     */
    public function clear()
    {
        $this->items = [];
        $this->write();
    }
    /**
     * Check if a item exist in cart.
     *
     * @param string $id
     * @param array  $attributes
     *
     * @return bool
     */
    public function isItemExists($id, $attributes = [])
    {
        $attributes = (is_array($attributes)) ? array_filter($attributes) : [$attributes];
        if (isset($this->items[$id])) {
            $hash = md5(json_encode($attributes));
            foreach ($this->items[$id] as $item) {
                if ($item['hash'] == $hash) {
                    return true;
                }
            }
        }
        return false;
    }
    /**
     * Add item to cart.
     *
     * @param string $id
     * @param int    $quantity
     * @param array  $attributes
     *
     * @return bool
     */
    public function add($id, $quantity = 1, $attributes = [])
    {
        $quantity = (preg_match('/^\d+$/', $quantity)) ? $quantity : 1;
        $attributes = (is_array($attributes)) ? array_filter($attributes) : [$attributes];
        $hash = md5(json_encode($attributes));
        if (count($this->items) >= $this->cartMaxItem && $this->cartMaxItem != 0) {
            return false;
        }
        if (isset($this->items[$id])) {
            foreach ($this->items[$id] as $index => $item) {
                if ($item['hash'] == $hash) {
                    $this->items[$id][$index]['quantity'] += $quantity;
                    $this->items[$id][$index]['quantity'] = ($this->itemMaxQuantity < $this->items[$id][$index]['quantity'] && $this->itemMaxQuantity != 0) ? $this->itemMaxQuantity : $this->items[$id][$index]['quantity'];
                    $this->write();
                    return true;
                }
            }
        }
        $this->items[$id][] = [
            'id'         => $id,
            'quantity'   => ($quantity > $this->itemMaxQuantity && $this->itemMaxQuantity != 0) ? $this->itemMaxQuantity : $quantity,
            'hash'       => $hash,
            'attributes' => $attributes,
        ];
        $this->write();
        return true;
    }
    /**
     * Update item quantity.
     *
     * @param string $id
     * @param int    $quantity
     * @param array  $attributes
     *
     * @return bool
     */
    public function update($id, $quantity = 1, $attributes = [])
    {
        $quantity = (preg_match('/^\d+$/', $quantity)) ? $quantity : 1;
        if ($quantity == 0) {
            $this->remove($id, $attributes);
            return true;
        }
        if (isset($this->items[$id])) {
            $hash = md5(json_encode(array_filter($attributes)));
            foreach ($this->items[$id] as $index => $item) {
                if ($item['hash'] == $hash) {
                    $this->items[$id][$index]['quantity'] = $quantity;
                    $this->items[$id][$index]['quantity'] = ($this->itemMaxQuantity < $this->items[$id][$index]['quantity'] && $this->itemMaxQuantity != 0) ? $this->itemMaxQuantity : $this->items[$id][$index]['quantity'];
                    $this->write();
                    return true;
                }
            }
        }
        return false;
    }
    /**
     * Remove item from cart.
     *
     * @param string $id
     * @param array  $attributes
     *
     * @return bool
     */
    public function remove($id, $attributes = [])
    {
        if (!isset($this->items[$id])) {
            return false;
        }
        if (empty($attributes)) {
            unset($this->items[$id]);
            $this->write();
            return true;
        }
        $hash = md5(json_encode(array_filter($attributes)));
        foreach ($this->items[$id] as $index => $item) {
            if ($item['hash'] == $hash) {
                unset($this->items[$id][$index]);
                $this->write();
                return true;
            }
        }
        return false;
    }
    /**
     * Destroy cart session.
     */
    public function destroy()
    {
        $this->items = [];
        if ($this->useCookie) {
            setcookie($this->cartId, '', -1);
        } else {
            unset($_SESSION[$this->cartId]);
        }
    }
    /**
     * Read items from cart session.
     */
    private function read()
    {
        $this->items = ($this->useCookie) ? json_decode((isset($_COOKIE[$this->cartId])) ? $_COOKIE[$this->cartId] : '[]', true) : json_decode((isset($_SESSION[$this->cartId])) ? $_SESSION[$this->cartId] : '[]', true);
    }
    /**
     * Write changes into cart session.
     */
    private function write()
    {
        if ($this->useCookie) {
            setcookie($this->cartId, json_encode(array_filter($this->items)), time() + 604800);
        } else {
            $_SESSION[$this->cartId] = json_encode(array_filter($this->items));
        }
    }
}

You only need this:

  • Initializing

      $cart = new Cart([
      // limitar quantidade items no carrinho
      'cartMaxItem'      => 0,
    
      // setar o máximo de quantidade de items no carrinho
      'itemMaxQuantity'  => 99,
    
      'useCookie'        => true,
    ]);
    
  • Add item

      //ID do produto
      $cart->add('1001');
    
  • Remove item

      //ID do produto
      $cart->remove('1001');
    
  • Get all cart items

      $allItems = $cart->getItems();
    
      foreach ($allItems as $items) {
         foreach ($items as $item) {
           echo 'ID: '.$item['id'].'<br />';
         }
      }
    
  • Total amount

      echo 'Total '.$cart->getTotalItem().' de itens no carrinho.';
    
  • 1

    Thanks for the tip my dear, I’m taking in a "didactic" way, doing several random projects and tals, but I already get you on these issues, I will focus on them in the future, only I want to master the basis of language before

  • 1

    It’s the easy and sure way, bro. As much as it doesn’t look.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.