Search code examples
phpsessionsession-variables

Php get/iterate the values of a particular session


Hy Guys I don't understand how create the code for save inside the sessions, these different values. This is an example of result of single session: First array contains two different products Second array contains the first name of user logged Third array contains the last name of user logged

enter image description here

Thx a lot.

i have solved it, thanks to your help I understand how the sessions works.

// fist and last name of user
$_SESSION['nome'] = $_POST['nome'];
$_SESSION['cognome'] = $_POST['cognome'];

// here add the article inside the session
$_SESSION['cart'][$_POST['productCode']] = [
'article' => $_POST['productName'],
'price' => $_POST['buyPrice'],
'quantity' => $_POST['num_prodotto']
];

// for add the quantity for the same product 
$_SESSION['cart'][$_POST['productCode']]['quantity']+=$_POST['num_prodotto'];

Solution

  • There's no need for 3 sessions, use one session.

    Your code can be something like:

    session_start();
    $_SESSION['nome'] = 'nome';
    $_SESSION['cognome'] = 'cognome';
    // for this case the cart is empty:
    $_SESSION['cart'] = [];
    
    // add a product:
    $article = 'A-1';
    $_SESSION['cart'][$article] = [
        'article' => $article,
        'price' => 100,
        'quantity' => 1,
    ];
    
    print_r($_SESSION);
    
    // add second product:
    $article = 'A-2';
    $_SESSION['cart'][$article] = [
        'article' => $article,
        'price' => 100,
        'quantity' => 1,
    ];
    
    print_r($_SESSION);
    
    // update quantity under article A-1:
    $article = 'A-1';
    $_SESSION['cart'][$article]['quantity'] += 1;
    
    print_r($_SESSION);