I have a database and I want to make sure that fields are not empty, and if not I want to save them into database with this sanitized function. So after fields are filled and sanitized I want to save them to database.
<?php
// Initialize variables to null.
$nameError ="";
$emailError ="";
// On submitting form below function will execute.
if(isset($_POST['submit'])){
if (empty($_POST["name"])) {
$nameError = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameError = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailError = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid or not
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email)) {
$emailError = "Invalid email format";
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
//php code ends here
?>
<!DOCTYPE html>
<html>
<head>
<title>Form Validation with PHP - Demo Preview</title>
<meta content="noindex, nofollow" name="robots">
<!--<link href="style.css" rel="stylesheet">-->
</head>
<body>
<div class="maindiv">
<div class="form_div">
<div class="title">
<h2>Form Validation with PHP.</h2>
</div>
<form action="index.php" method="post">
<h2>Form</h2>
<span class="error">* required field.</span><br/>
Name:
<input class="input" name="name" type="text" value=""><br/>
<span class="error">* <?php echo $nameError;?></span><br/>
E-mail:
<input class="input" name="email" type="text" value=""><br/>
<span class="error">* <?php echo $emailError;?></span><br/>
<input class="submit" name="submit" type="submit" value="Submit">
</form>
</div>
</body>
</html>