Jump to content

PHP Session + Array


laqutus

Recommended Posts

Hi there, I am pulling my hair out again, been trying to solve this for an hour or so now:

 

Basically, I have items (wooden doors) on a product page, each have differing size options attached to the item.

 

When I add a prodcut to the cart I add the options to an array grab the entire post and populate a session array. The problem I am having is when I try to add a further item it overwrites the origianal, as to only store one items details in the array. How can I add another line to the array?

 

<? foreach ( $_POST as $key) {

      echo $key;

      echo "<br>";

      $_session['cart'][] = $key;

}

echo '<pre>';

            print_r($_session);

            echo '</pre>';

?>

 

This does work any outputs: Array

(

    [cart] => Array

        (

            [0] => 32

            [1] => 33

            [2] => 34

            [3] => 35

            [4] => Enquire

        )

 

)

 

This would be all the data needed (ids for the products from which I can get the sizes)

 

But If I jump back to the products page, select a few new sizes from a differing product and click submit it overwitrites the original data? How can I get past this? How can a "new line" in effect be added to the session?

 

Sorry if this is complex, not been coding long (very stressful dont know how you guys do it!!)

 

Thanks in avance if you need any more info I can supply,

 

Kind regards,

Sarah

 

 

 

 

Link to comment
https://forums.phpfreaks.com/topic/150730-php-session-array/
Share on other sites

As shlump says, put $_SESSION in capitals, but the following should (hopefully) resolve your problem.

 

<?php
session_start();

$nextCartKey = (isset( $_SESSION['cart'] ) ? count( $_SESSION['cart'] ) : 0);
foreach ( $_POST as $key) 
       $_SESSION['cart'][$nextCartKey] = $key; 

    echo '<pre>'; 
    print_r($_session); 
    echo '</pre>';
?>

 

Hope this helps :).

Link to comment
https://forums.phpfreaks.com/topic/150730-php-session-array/#findComment-792098
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.