开发者

Adding item to array PHP

开发者 https://www.devze.com 2022-12-08 10:48 出处:网络
I\'m building a shopping cart for a school assignment. I\'m pretty much there except for adding the items to the cart variable.

I'm building a shopping cart for a school assignment. I'm pretty much there except for adding the items to the cart variable.

I've set up my cart session with: $_SESSION['temp_session'] = array();

and then, when a item is added to the cart, this code is executed

if (isset($_POST['addtocart'])) {
            $item_name = $_POST['item_name'];
            $price = $_POST['price'];
            $qty = $_POST['qty'];

            $newItem = $item_name.":".$price.":".$qty;
            //echo $newItem;

            if (isset($_SESSION['shop_session'])) {
                array_push($shop_session, $newItem);
                //header('Location: cart.php');
                print_r($shop_session);
            }
            else {
                array_push($temp_session, $newItem);
                //header('Location: login.php?notLoggedIn=tr开发者_高级运维ue');
                print_r($temp_session);
            }
        }

it all seem s to be working fine (i can print out $newItem and it contains the elements) but when I try to add $newItem to either $shop_session or $temp_session and then print them out, there array is empty.

Is this something to do with the way I'm using array_push() ?

Thanks


Is your RegisterGlobals is on? If not you must use

            if (isset($_SESSION['shop_session'])) {
                    array_push($_SESSION['shop_session'], $newItem);
                    //header('Location: cart.php');
                    print_r($_SESSION);
            }
            else {
                array_push($_SESSION['temp_session'], $newItem);
                    //header('Location: login.php?notLoggedIn=true');
                    print_r($_SESSION);
            }


You can't type

$_SESSION['temp_session'] = array();

and expect to have a variable named $temp_session. All you have is an array ($_SESSION) which contains an element (with key name temp_session), which in turn is an array as well.

In order to have the desired results you need an additional line, such as:

$temp_session = $_SESSION['temp_session'];

and when you update that, back again into your session:

$_SESSION['temp_session'] = $temp_session;
0

精彩评论

暂无评论...
验证码 换一张
取 消