1

I have this shopping cart page coded, but i am clueless about how to acces the product id from session in another page? Anyone please help me! I'm beginner so if you please give me example code too it'd help me a lot.

<?php
    session_start();
    $product_ids = array();
//session_destroy();

//check if Add to Cart button has been submitted
if(filter_input(INPUT_POST, 'add_to_cart')){
    if(isset($_SESSION['shopping_cart'])){

        //keep track of how mnay products are in the shopping cart
        $count = count($_SESSION['shopping_cart']);

        //create sequantial array for matching array keys to products id's
        $product_ids = array_column($_SESSION['shopping_cart'], 'id');

        if (!in_array(filter_input(INPUT_GET, 'id'), $product_ids)){
        $_SESSION['shopping_cart'][$count] = array
            (
                'id' => filter_input(INPUT_GET, 'id'),
                'name' => filter_input(INPUT_POST, 'name'),
                'price' => filter_input(INPUT_POST, 'price'),
                'quantity' => filter_input(INPUT_POST, 'quantity')
            );   
        }    
    }
    else { //if shopping cart doesn't exist, create first product with array key 0
        //create array using submitted form data, start from key 0 and fill it with values
        $_SESSION['shopping_cart'][0] = array
        (
            'id' => filter_input(INPUT_GET, 'id'),
            'name' => filter_input(INPUT_POST, 'name'),
            'price' => filter_input(INPUT_POST, 'price'),
            'quantity' => filter_input(INPUT_POST, 'quantity')
        );
    }
}
?>
3
  • 2
    as long as you have session_start(); on the other page you access the $_SESSION array like any other array Commented Jun 13, 2018 at 23:30
  • 1
    What other page? Please show the part of code that has problem accessing $_SESSION variable. Commented Jun 13, 2018 at 23:59
  • 1
    I mean if i want to access the product id from session variable, what will be the code? Commented Jun 14, 2018 at 1:07

1 Answer 1

1

Use the same code you have here on the other page to get the product_ids

//other page
session_start();
$product_ids = array_column($_SESSION['shopping_cart'], 'id');
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.