Retaining data in HTML form
I have an HTML form. Let's say I fill out all the fields and submit it (PHP 开发者_C百科script runs here). Then I want to go back to the form using "Back" button of my browser. What I see is the empty form. What do I do to have the entered data retain on the page after I come back to it using "Back" button of the browser?
Thank you!
If you use the "Back" button of your browser then your browser is responsible for re-populating your form data.
Usually that functionality is handled by the browser, however if you want to "force" the fields to always be pre-filled with the user's data, you can store the $_POST data in a session variable and use that to load the form.
Example:
// submission page
session_start();
if(isset($_POST)){
// save the posted data in the session
$_SESSION["POST"] = $_POST;
}
Then on the actual form page, you can check to see if session data exists. It won't if the form is being loaded the first time, but it will if the user submits the form and then presses the browser back button:
// form page
session_start();
if(isset($_SESSION["POST"])){
// previous POST data has been saved
// build the form with pre-defined values from $_SESSION
...
} else {
// no previous data
// build the form without pre-defined values
...
}
Note that you must call session_start() before outputting any HTML.
Store the value in a session
session_start();
//form so that you have all the potential forms in a single session array
//form_1 to identify the form in question
if(!empty($_POST)){
$_SESSION['forms']['form_1'] = $_POST;//if this is for the public internet, then I would really consider making sure that the posted data matches the received data... (and that its comming from YOUR form), which is way too long to post here...
}
then on the form page
<input name="flowers" value="<?php echo if(isset($_SESSION['forms']['forms_1']['flowers'])){ echo htmlspecialchars($_SESSION['forms']['forms_1']['flowers']);} ?>" />
obviously the above can be simplified, but for a example's sake it's better this way.
(make sure to clean out the old form data eventually)
You can potentially store the data in the session, and re-populate it back using PHP sessions. You should create a separate back button that takes you to the previous page.
Example:
Storing data:
$_SESSION['data'] = $_POST['item1'];
In the HTML Forms:
<input type="text" name="someinput" value="<?=$_SESSION['data']?>" />
精彩评论