skip to Main Content

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.

3

Answers


  1. Remember, if you do use echo then make sure you escape the output, ie

    echo htmlspecialchars($_POST['name']);
    

    otherwise you risk injection attacks

    Login or Signup to reply.
  2. 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>
    
    Login or Signup to reply.
  3.  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']) : '' ?>">
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search