Reputation: 23
I wanted to store list of users from php form in a php session I defined an empty array at the beginning of the session and tried to collect the user names at every submit.
session_start();
$persons=array();
if (isset($_POST)) {
$_SESSION['val']=$_POST['val'];
$persons=$_SESSION['val'];
}
foreach($persons as $d){
echo $d;
echo '</br>';
}
<form action="exam.php" method="post">
Enter a new Person: <input type="text" name = "val">
<input type="submit" name = "send">
</form>
I expected to have the list of persons I submitted returned from the array but every time I submit, the last submit replaces the first one.
Upvotes: 1
Views: 1116
Reputation: 2661
You are overwriting the array each time:
$persons = $_SESSION['val'];
In order to push data to an array in php you must do it this way:
$persons[] = $_SESSION['val'];
If what you want to is store all persons on session, without overwriting them each time you first need to check if session exist, if not, create it.
if(!isset($_SESSION['persons'])){
$_SESSION['persons'] = array()
}
And then change how you store the info in the session, example:
$_SESSION['persons'][] = $_POST['val'];
Then you can do:
foreach($_SESSION['persons'] as $d){
echo $d;
echo '</br>';
}
So the code will look like:
session_start();
$persons=array();
if(!isset($_SESSION['persons'])){
$_SESSION['persons'] = array();
}
if (isset($_POST)) {
$_SESSION['persons'][] = $_POST['val'];
}
foreach($_SESSION['persons'] as $d){
echo $d;
echo '</br>';
}
<form action="exam.php" method="post">
Enter a new Person: <input type="text" name = "val">
<input type="submit" name = "send">
</form>
I did not compile the code, check for syntax errors, but the procedure is right.
Upvotes: 1