PHP Save entered values ​​after validation error

I have a simple form that needs validation.
I did this using the empty() function. If the verification fails, the user receives a warning. As soon as this warning is generated, all entered values ​​disappear.

I would like to save them.

This is what I did:

 <form id="" name="" action="<?php echo get_permalink(); ?>" method="post"> <table> <tr> <td> Name:<input type="text" id="name" name="name"> </td> </tr> <tr> <td> <input class="submit-button" type="submit" value="Send" name="submit"> </td> </tr> </table> </form> <?php if($_POST["submit"]){ if (!empty ($_POST["name"])){ // do something }else{ ?> <script type="text/javascript"> alert('U heeft niet alle velden ingevuld. Graag een volledig ingevuld formulier versturen'); </script> <?php } ?> 
+5
source share
3 answers

Pass the entered value as the default value for input:

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

The easiest way is for each input field:

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

It checks if you have already submitted the form once, if this value is marked in the text box.

+1
source

Unusually, I seem to be working on a similar one, and used the following data so that the form data is available after the form is submitted. It uses a session variable to store the POST results 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')."' />"; 
+1
source

Source: https://habr.com/ru/post/1234255/


All Articles