November 18, 2010

Using form contents to add values to $_SESSION array

Question by BigRob

I’m trying to make a page that takes a form submission and adds the contents as a new value in the $_SESSION() array, what seems to be happening though is the value is being overridden.

The form has 3 text inputs named a, b and c and refreshes the page on submission. What tells me it’s being replaced is $_SESSION[0] will display 1 2 and 3 as defined below, then the next row defined by $_POST will be the same but with the array values replaced by the last submitted values rather than adding the last submitted as another row.

<form action="test2.php" method="post">
<input type="text" name="a">
<input type="text" name="b">
<input type="text" name="c">
<input type="submit" value="Submit">
</form>

<?php
    if (isset($_POST['a']))
    {
     $a = $_POST['a'];
     $b = $_POST['b'];
     $c = $_POST['c'];
     $order = array('a' => $a, 'b' => $b, 'c' => $c);
     $_SESSION[0] = array('a' => 1, 'b' => 2, 'c' => 3);
     $_SESSION[] = $order;
     $count = count($_SESSION);
     for ($i = 0; $i < $count; $i++) {
      echo "w: " . $_SESSION[$i]['a'] . "n";
      echo "h: " . $_SESSION[$i]['b'] . "n";
      echo "p: " . $_SESSION[$i]['c'] . "n";
      echo "<br />";
      }
    }
?>

Would be extremely grateful for any help,
Thanks

Answer by Nick Pyett

It looks to me like you are trying to add a new array to a new $_SESSION var each time the form is submitted. The method you are using will only add the value to the $_SESSION array for that page load – it won’t actually be in the $_SESSION array! Confusing right? So either of these won’t work…

$_SESSION[] = 'value or array';
$_SESSION[1] = 'some other stuff';

But this will, due there being text in the $_SESSION key (and don’t forget to start the session).

session_start();
$next = count($_SESSION) + 1;
$next = 'foo' . $next;
$_SESSION[$next] = 'bar' . $next;

This will generate the below for “print_r($_SESSION)”.

Array ( [foo1] => barfoo1 [foo2] => barfoo2 [foo3] => barfoo3 [foo4] => barfoo4...

Answer by Starx

Most simplest way of adding form values would be

$_SESSION['form'] = $_POST; //once the form is posted

Then access the values using

$_SESSION['form']['fieldname'];

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!