In a PHP web page, when flling the form and some of the fields are filled incorrectly, I need to return to the same page and auto-fill all the fields that were prefiously filled by the user. How do I set the values of the fields?
I tried using the $_POST method and echo but the error was that the key I used was undefined.
CodePudding user response:
Remember, if you do use echo
then make sure you escape the output, ie
echo htmlspecialchars($_POST['name']);
otherwise you risk injection attacks
CodePudding user response:
You can store values in an array called data$ And if there is an error, return this array to the page and use the value method to fill in the pre-filled values. Example
$data =[
'name' => $_POST['name']
];
if(empty($data['name']){
$data['name_err']= "error name";
}
And on the desired page:
<input value="<?php echo $data['name'] >?">
<span><?php echo $data['name_err'] <span>
CodePudding user response:
You can use a session to store the form values.
<?php
// Start the session
session_start();
// Store values in session//
$_SESSION['form'] = ['first_name' => isset($_POST['first_name']) ? $_POST['first_name'] : '', 'last_name' => isset($_POST['last_name']) ? $_POST['last_name'] : '', ];
?>
<input name="first_name" value="<?php echo isset($_SESSION['form']['first_name']) ? htmlspecialcharc($_SESSION['form']['first_name']) : ''; ?>">
<input name="last_name" value="<?php echo isset($_SESSION['form']['last_name']) ? htmlspecialcharc($_SESSION['form']['last_name']) : '' ?>">