简体   繁体   中英

How to store user input from php form in php session

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM