'PHP contact form keep input fields if error, otherwise clear

I want my contact form input fields to save the user's inputs if there's an error, otherwise have them cleared if the email goes through. Right now it works except when the email is sent the fields are still filled in. I could refresh the page but then it doesn't show the 'Your email has been sent' message.

Here's my form:

<form class="contact-form" action="" method="post">
<input type="text" name="name" value="<?php if(isset($_POST["name"])) echo $_POST["name"]; ?>" />
</form>

I tried adding something to my php code that handles the email business - if the message was sent, unset($_POST["name"]), and also adding to this form input's php else echo ''; but that didn't seem to work. It seems the variable was still set.



Solution 1:[1]

You should set error flag while error occurred. try this

$error=false; if(isset($_POST['submit'])){

$msg =  $_POST['msg'];

if(mail("[email protected]","My subject",$msg)){

    
}else{
    
    $error = "mail does not sent";
}

}

" />

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Manendra