Ross
Ross

Reputation: 141

PHP - Using $_POST to update session array

I'm new to using PHP sessions and I'm having trouble updating a session array using the form $_POST method.

Basically, each button has a value that I want to add to the array $_SESSION['items'] on each click. However, currently what is happening is the array gets reset and replaced by the last selected value.

Here's what I've got so far:

<?
session_name("test");
session_start();
?>


<form method="post">
    <button type="submit" name="item[]" value="Item 1">Item 1</button>
    <button type="submit" name="item[]" value="Item 2">Item 2</button>
</form>


<?
$_SESSION['items'] = array();
array_push($_SESSION['items'], $_POST['item']);
print_r($_SESSION['items']);
?>


Any help would be appreciated.
Thanks!

Upvotes: 0

Views: 1199

Answers (4)

EternalHour
EternalHour

Reputation: 8621

$_SESSION is already an array, no need to declare it. At the top of the script you have already created $_SESSION['test']

Try

<?
array_push($_SESSION['test'], $_POST['item']);
print_r($_SESSION['test']['item']);
?>

You may also need to reverse these for it to work.

session_start();
session_name("test");

Upvotes: 0

matt_jay
matt_jay

Reputation: 1271

It looks like you're resetting the Session array with

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

Leaving that bit out seems to do the trick.

I also suggest you change the name of the buttons to just "item", as you otherwise add an array to your session array with each click and not just a single value. Unless of course that's exactly what you intended.

The new script would look like this:

<?
session_name("test");
session_start();
?>


<form method="post">
    <button type="submit" name="item" value="Item 1">Item 1</button>
    <button type="submit" name="item" value="Item 2">Item 2</button>
</form>


<?
array_push($_SESSION['items'], $_POST['item']);
print_r($_SESSION['items']);
?>

Upvotes: 0

Fallen
Fallen

Reputation: 4565

$_SESSION['items'] = array(); this line is resetting the $_SESSION['items'] every time the page is loaded. If you want to initialize the array, try,

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

instead.

Upvotes: 1

In this case you could try something like:

$_SESSION['items'] = $_POST['items'];

If you wanted to add an array instead of a value to the session you can try something like this:

$items= new array(
    "1" => "item1",
    "2" => "item2");
$_SESSION['items'] = $items;

Upvotes: 0

Related Questions