saftutorials.com
PHP Form Submit

After creating HTML form, fill the input fields of form by the users and then click on submit button of the form, at that time these actions are performed.

Check that input fields value is correct or not filled by the user.
If input fields value is not correct then we force the users that enter valid data
After that, the data is sent to the same or different page by using HTTP post method and process the data.

Below is the complete example for submit form

<!DOCTYPE html>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $mobileErr = "";
$name = $email = $gender  = $mobile = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
 $nameErr = "Name is required";
}else {
 $name = validate_input($_POST["name"]);
}
if (empty($_POST["email"])) {
 $emailErr = "Email is required";
}else {
 $email = validate_input($_POST["email"]);
 // check if email address is invalid
 if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $emailErr = "Invalid email format"; 
 }
}
if (empty($_POST["mobile"])) {
 $mobileErr = "";
}
else {
 $mobile = validate_input($_POST["mobile"]);
// check if email address is valid
 if (!filter_var($mobile, FILTER_VALIDATE_INT)) {
    $mobileErr = "Invalid mobile no"; 
 }
}
if (empty($_POST["gender"])) {
 $genderErr = "Gender is required";
}else {
 $gender = validate_input($_POST["gender"]);
}
}
function validate_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>Registration Form</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table>
<tr>
 <td>Name:</td>
 <td><input type="text" name="name"><span class="error">* <?php echo $nameErr;?></span></td>
</tr>
<tr>
 <td>Email Id: </td>
 <td><input type="text" name="email"><span class="error">* <?php echo $emailErr;?></span></td>
</tr>
<tr>
 <td>Mobile:</td>
 <td><input type="text" name="mobile"><span class="error"><?php echo $mobileErr;?></span></td>
</tr>
<tr>
 <td>Sex:</td>
 <td>
    <input type="radio" name="gender" value="female">Female
    <input type="radio" name="gender" value="male">Male
    <span class="error">* <?php echo $genderErr;?></span>
 </td>
</tr>
<tr><td><input type="submit" name="submit" value="Submit"></td></tr>
</table>
</form>
</body>
</html>


Find us on

Facebook Google Plus Twitter Pinterest YouTube

web statistic