Php – Clear html text fields

mysqlphp

I have an HTML form for submitting and retrieves data from MySQL database with two buttons, "Save/Submit" and "New/Reset"
It fetch data correctly from MySQL database but when I click on New/Reset button for new contact entry it couldn't clear forms text fields. My HTML and PHP codes are as under:

<?php
//Database Connection file.
include'connect.php';
$sql = mysql_query("SELECT * FROM contact_list WHERE id='1'");
While($result = mysql_fetch_assoc($sql)){
   $fname = $result['fname'];
   $lname = $result['lname'];
   $email = $result['email'];
   $contact = $result['contact'];
}

if(isset($_POST['fname'])&&isset($_POST['lname'])&&isset($_POST['email'])&&
isset($_POST['contact'])){
   $fname = $_POST['fname'];
   $lname = $_POST['lname'];
   $email = $_POST['email'];
   $contact = $_POST['contact'];

if($sql = mysql_query("INSERT INTO contact_list VALUES ('', '$fname', '$lname',
'$email', '$contact')")){
   echo'Contact Save Successfully.';
}else{
   echo'Contact not save.';
}
}
?>
<html>
<form action="sample.php" method="POST">
   First Name:<input type="text" name="fname" value="<?php if(isset($fname))
   {echo $fname;}?>">
   Last Name:<input type="text" name="lname" value="<?php if(isset($lname))
   {echo $lname;}?>">
   Email:<input type="text" name="email" value="<?php if(isset($email))
   {echo $email;}?>">
   Contact:<input type="text" name="contact" value="<?php if(isset($contact))
   {echo $contact;}?>">
//Clean all fields of forms for new entry.
   <input type="reset" value="New">
//Save or submit form data into mysql database
   <input type="submit" value="Save">
</form>
</html>

Best Solution

You can do this easily by using jQuery

<html>
<head>
<script type="text/javascript">
$(document).ready(function() {
    $("#btnReset").click(function(){
       $("#fname").val("");
       $("#lname").val("");
       $("#email").val("");
       $("#contact").val("");
    }); 
});

</script>
</head>
<form action="sample.php" method="POST">
   First Name:<input type="text" name="fname" value="<?php if(isset($fname))
   {echo $fname;}?>" id="fname">
   Last Name:<input type="text" name="lname" value="<?php if(isset($lname))
   {echo $lname;}?>" id="lname">
   Email:<input type="text" name="email" value="<?php if(isset($email))
   {echo $email;}?>" id="email">
   Contact:<input type="text" name="contact" value="<?php if(isset($contact))
   {echo $contact;}?>" id="contact">
//Clean all fields of forms for new entry.
   <input type="reset" value="New" id="btnReset">
//Save or submit form data into mysql database
   <input type="submit" value="Save" id="btnSave">
</form>
</html>
Related Question