3

For about 2 hours i'm struggling with this problem. I want to insert my $_POST variables in a $_SESSION array,and append each new data sent from the form to the session variable. Now,when i define my session variable as a array,do i say like this?
$_SESSION['name'];
or like this
$_SESSION['name'] = array();

I have two POST variables,and i want to insert each one in a session array.

Here is the form:

<form action="action.php" method="POST" >
<label>Moovie name: <input type="text" name="name" /></label><br />
<label>Price: <input type="text" name="price" /></label><br />
<input type="submit" value="Send" />
</form>

And here is action.php

<?php

session_start();

$_SESSION['name'] = array();
$_SESSION['price'] = array();

$name = $_POST['name'];
$price = $_POST['price'];

array_push($_SESSION['name'], $name);
array_push($_SESSION['price'], $price);

print_r($_SESSION['name']);
echo "<br>";
print_r($_SESSION['price']);

?>

Note: If i say

$_SESSION['name']; instead of $_SESSION['name'] = array();

i get Warning: array_push() expects parameter 1 to be array, null given in action.php
Again, is $_SESSION['name'] an array from the beginning?

Iliescu Alex
  • 83
  • 3
  • 8
  • Check if [`is_array`](http://www.php.net/manual/en/function.is-array.php), if not, then set them to arrays and continue, if it has already been initialized, that `= array()` code won't be ran, so you won't null it out. (or, with how PHP works, you may simply just use `$_SESSION['name'][] = $name;` etc and if it isn't an array, it will be made in to one.) – Jon Mar 17 '13 at 11:38
  • @Jon `is_array()` will still trigger a notice is the key doesn't exist at all, use `isset()` as well/instead: `if (!isset($_SESSION['name'])) { $_SESSION['name'] = array(); }` – DaveRandom Mar 17 '13 at 11:42

1 Answers1

3

You are emptying the session arrays every time this script runs.

To avoid this, check if the arrays are already present in the session:

<?php

session_start();


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


$name = $_POST['name'];
$price = $_POST['price'];

array_push($_SESSION['name'], $name);
array_push($_SESSION['price'], $price);

print_r($_SESSION['name']);
echo "<br>";
print_r($_SESSION['price']);

?>
matt
  • 359
  • 1
  • 7