PHP Keep entered values after validation error

The easiest way would be to this for every input field:

<input type="text" id="name" name="name" value="<?= isset($_POST['name']) ? $_POST['name'] : ''; ?>">

It checks if you already submitted the form once, if so put the value in the textbox.


Bizarrely I happen to be working on a similar thing and have been using the following to ensre that form data is available after submission of the form. It uses a session variable to store the results of the POST and is used as the value in the form field.

/* Store form values in session var */
if( $_SERVER['REQUEST_METHOD']=='POST' ){
    foreach( $_POST as $field => $value ) $_SESSION[ 'formfields' ][ $field ]=$value;
}

/* Function used in html - provides previous value or empty string */
function fieldvalue( $field=false ){
        return ( $field && !empty( $field ) && isset( $_SESSION[ 'formfields' ] ) && array_key_exists( $field, $_SESSION[ 'formfields' ] ) ) ? $_SESSION[ 'formfields' ][ $field ] : '';
}

/* example */
echo "<input type='text' id='username' name='username' value='".fieldvalue('username')."' />";

Pass that entered value as a default value to input:

<input type="text" id="name" name="name" value="<?php echo isset($_POST["name"]) ? $_POST["name"] : ''; ?>">