Link to home
Start Free TrialLog in
Avatar of TacomaVA
TacomaVA

asked on

Saving data in a form after it's been submitted

I built a simple form in HTML and I am using PHP to collect the data and then write it to a text file.  After clicking the submit button, all of the fields are cleared.  Is there a way to change this so that after the submit button is pressed, the fields still remain populated with their data?
Avatar of Beverley Portlock
Beverley Portlock
Flag of United Kingdom of Great Britain and Northern Ireland image

OK, assuming that the form resides in a .php script you do this

<?php

if script submitted form then
    capture fields
    writ to file
endif


HTML form

?>

So the trick is that the form's action is the page it resides in. So we would have the following

<?php

// Check for SUBMIT button being pressed
//
if ( isset( $_POST['submit'] ) ) {

     // Collect variables from form. These are the "name" attributes
     // in the HTML input fields
     //
     $value1 = $_POST['field1'];
     $value2 = $_POST['field2'];

     // Write to file
     //
     $fp = fopen("myfile.txt", "w");
     fputs( $fp, "value 1 is $value1 and value2 is $value2");
     fclose( $fp );

}

?>
<html>
    <head>
         .... etc

    <form action='<?php echo $_SERVER['PHP_SELF']; ?>' method='post'>

         .. other stuff
         <input name='field1' type='text' value='' />
         <input name='field2' type='text' value='' />

         <input name='submit' type='submit' value='Process my form' />

    </form>

         .... etc
</html>


There is a bit more to it than that but that is the basics. Hopefuuly you can adapt it easily enough.
ASKER CERTIFIED SOLUTION
Avatar of leakim971
leakim971
Flag of Guadeloupe image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks for the points! happy new year!