Search code examples
phpformssticky

Proper syntax to Make type index form field sticky in PHP


I have to include some form type=index fields in a funciton eg. firstname, lastname. The form uses a separate handle.php page. I can't figure out how to make it sticky (retain the last value entered if I refresh the page). Because I refresh the page back to the form if there is an error input, and want to see the last input fields entries retained. I have tried $_SESSION['fname'] and $_POST['fname']. Neither seems to work...

This is without sticky

echo "<tr><td>First Name:<input type='text' name='fname' value=''></td>";

This is what I think works if not already within a php block

<td>First Name:<input type='text' name='fname' placeholder='First Name' value="<?php if(isset($_SESSION['fname'])) echo ;?>" ></td>

Solution

  • You are close!

    Your example is missing the argument for echo. Try this:

    <?php if(isset($_SESSION['fname'])) echo $_SESSION['fname'];?>
    

    However, a form will never submit to the $_SESSION by default.

    if you have <form action='handle.php' method='get'> your variables will be in the $_GET superglobal, and if you have method=post they are available in $_POST i.e. `$_POST['fname']

    you have to manually put things in the session, i.e.

    $_SESSION['fname'] = $_POST['fname'] (we just copied the post fname value into the session)

    Usually for something like validating a form it is better to use $_REQUEST, $_POST, or $_GET instead of putting the variables in the $_SESSION. The $_SESSION gets crowded since it remembers everything, and form validation doesn't usually need to be remembered for more than 1 request.

    $_POST variables won't be remembered if you refresh the page with the browser. The $_POST variable will only be posted if you post the form (submit it) to the server. If you are trying to remember them for a browser refresh, you would have to manually copy the variable into the session like the example above.

    If you just want to access your variables on your next page, they will be available in the $_POST or $_GET superglobals, depending on your form.

    If you want to pass them back to the form page, the method to do so depends on how you are redirecting. You either need to post them or add them to the url, and access them in your form page from the superglobals.