Search code examples
phphtmltextfield

Keep text in text field after submit


I'm building a form, and I want that all the inserted values will be kept, in case of form submit failure. This is my code:

<?php
$error = "";
$name = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
   $name = $_POST["name"];

   // Verify $_POST['name'] greater than 4 chars
   if ( strlen($name) < 4 ){
        $error= 'Name too short!';
    }
}
?>

<html>
<head>
</head>
<body>
    <form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" name="myForm" id="idForm">
       <input type="text" placeholder="Name" id="name" name="name" value=""/>
       <input type="submit" value="submit"/>
    </form>
        <?php 
            echo "<h2>Input:</h2>"; 
            echo $name;
            if($error) {
                // No Update AND refresh page with $name in text field
                echo "<br/>" . $error; 
            } else {
                // Update name in DB
            }
       ?>
</body>
</html>

I would like that name field keeps the inserted input text, after submit. I tried to do with php code in input value but doesn't work. Any ideas?


Solution

  • Solved. This is the solution that I was looking for. I added in value tag of input the following:

    <?php if (isset($_POST['name'])) echo $_POST['name']; ?>
    

    Therefore input field would look like:

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

    Thanks for your responses, helped me.