I was looking to find a way in php to retain form data. After poking around the net through various tutorials, I found a way. I can script some basic things, but am still quite a novice at php.

So here’s what i found I could do, with the help of a blog entry at scriptygoddess.

For this, I will use a $_SESSION() to help carry the data throughout the pages. This requires that the following code be placed at the top of all the pages involved:

< ?php
session_start();
header("Cache-control: private"); // IE 6 Fix.
?>

Now we need the form page(with the above code in it too):

<form method="post" action="preview.php">
First Name:<input type="text" name="First_Name" value="<? print("$_SESSION[First_Name]");?/>" /><br />
Last Name:<input type="text" name="Last_Name" value="<? print("$_SESSION[Last_Name]");?/>" /><br />
<input type="submit" value="submit"/>
</form>

When submit is pushed, you can see the action takes us to a preview page(preview.php). This page will display what youve entered in the form, and give you the option to go back and edit your data, or agree, and continue processing the form.

< ?php
//preview.php
 
// Start session
session_start();
header("Cache-control: private"); // IE 6 Fix.
 
// actions to take from buttons
if (isset($_POST["goBack"])) { // Go Back and Edit
    header("Location: form.php");
} else {
    if (isset($_POST["Send"])) { // OR process the form
        header("Location: process.php");
    }
}
 
// Dynamically Assign Key & Value to each Post
foreach($_POST as $key=>$value){
    $_SESSION[$key]=$value;
}
?>

The key element to holding the data to fill back in the form with the data you entered lies in this bit of code:

// Dynamically Assign Key & Value to each Post
foreach($_POST as $key=>$value){
    $_SESSION[$key]=$value;
}

What this does is take all the data you entered “$_POST” and turn it into an array. It first assigns it a $key and also holds the value of it i.e. =>$First_Name. So in this example the $_POST array looks like:
array([0]=>what_you_entered_for_the_first_name[1]=>what_you_entered_for_the_last_name)

So when you hit ‘edit’ this will cause:

First Name:<input type="text" name="First_Name" value="<? print("$_SESSION[First_Name]");?/>" />

to display what was entered originally.


One Response to “Retaining Form Data”

  1. Beginnercode.com » $_SESSION() Checkbox doesn’t hold state Says:

    […] I’ve been working on getting forms to hold their data when the back button is pushed. It’s been slow going. I thought I had it down (This entry). But when it came to checkboxes, and selects, I was in for a surprise. Most the code is pretty fundamental. I was able to get selects to work, by making them dynamic and conditionally adding the “selected” attribute to the selected item. […]

Post A Comment