简体   繁体   中英

cannot put new string into array

I have a form when the user types something in, it will appear on the screen. I kept the text that the user typed in a variable called $output , then I tried to put each $output into an array called $arrayText , my objective is to have the user type in something and click a button, then the user's text appears on the screen and when he tries for the second time, the first text is still there while the new one will be on the next line. However, it works only for the first time. For the second time, it replaces the second text with the old one, here is my code

if (isset($_POST['putContents'])) { 
  $output = $_POST['contents'];
  test();

}
function test()
{
static $arrayText = array();
    global $output;
    $arrayText[]= $output;
    for($i = 0; $i < count($arrayText); $i++){
    echo $arrayText[$i];
    echo "<br>";
  }
}

}

?>

thanks for any help in advance

By executing a second time your script your $_POST will only have the values of your last submit which in your case will override your array.

If you want to store data beyond the current process you'll have to store the date somewhere other then the $_POST global.

I'm suggesting you use sessions for this as a database query would certainly over blow your needs. Use:

session_name("admin");
session_start();
if(empty($_SESSION["yourOldText"])) $_SESSION["yourOldText"]=$_POST["userinput"];

and if you want to access your old data then you can just use $_SESSION["yourOldText"]

You can't "collect" the user input line-by-line into an array after each time he presses the submit button. The lines must be persisted (stored) somewhere. You can store each line as a record in a database or in a session cookie as suggested. I would persist the state by storing the entered lines in hidden input tags inside your form:

<input type="hidden" name="line[0]" value="What the user typed in first" />
<input type="hidden" name="line[1]" value="The second line that was typed in" />
<input type="text" name="contents" value="" />

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