开发者

How can I stop PHP from replacing the variable everytime the form is updated?

Basic question - I have a text area with a submit button that is linked to the variable $ListItem.

Further down the page I want to print $ListItem in a <li> and everytime something new is entered in the text area, I want to assign it a new variable ($ListItem2 perhaps?) and then print it below the previous one.

With my current code, every time a new string is ente开发者_C百科red in the text area, it replaces the existing variable:

<?php
$ListItem = $_POST["ListItem"];
?>

<form method="post" action="<?php echo $PHP_SELF;?>">
<textarea name="ListItem" cols=80 rows=6></textarea> <br />
<input type="submit" value="Submit"> <br />
</form>

<li><?php echo $ListItem; ?></li>

Am I going to have to use a database?


You could pop it onto an array stored in the session:

$_SESSION["vars"][] = $_POST["ListItem"];

This would keep the full history through future submits. Printing them would be as simple as cycling through the session array:

foreach ($_SESSION["vars"] as $var) {
  echo "<p>{$var}</p>";
}

Remember to start the session before anything else takes place:

session_start();

Detailed Explanation (requested in comments)

The first item in my answer was an example of appending another item onto an array. If we start with an empty array:

$myArr = array();

We can add new entries with the following syntax:

$myArr[] = "Foo";
$myArr[] = "Bar";

Our array now has two items within it. This would be the same as doing this:

$myArr = array("Foo", "Bar");

Using the double-bracket method is a quick way to place more items into the array, while keeping what is presently there to begin with. There are other ways to do this, for instance you could use the array_push() function:

array_push($myArr, "Foo");

This does the same thing as our previous example though, so it doesn't offer much of a difference. Stepping back now, we note that our array is stored within the SESSION array. This is an array that is useful for storing data that will be used frequently during a users visit to your website. It's often times a better alternative to storing trivial data in a database, and making calls upon each request.

Again, we have an array:

$_SESSION["vars"] = array();

Basically all we're doing is setting an array within an array, handled by the key "vars". The key is important so we can quickly reference this data at a later time. And back to our first line of code, you can now make more sense of what we were doing:

$_SESSION["vars"][] = $_POST["ListItem"];

So all this is doing is adding the new value of $_POST["ListItem"] onto the array stored within $_SESSION["vars"] where it can later be retrieved.


Global Session Array

I would append the text area data to a global session array.

Eventually you will want to use a database.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜