html - php inserting data with filter and validation
913
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 >
<div >
<div >
<h2>Form Validation with PHP.</h2>
</div>
<form action="index.php" method="post">
<h2>Form</h2>
<span >* required field.</span><br/>
Name:
<input name="name" type="text" value=""><br/>
<span >* <?php echo $nameError;?></span><br/>
E-mail:
<input name="email" type="text" value=""><br/>
<span >* <?php echo $emailError;?></span><br/>
<input name="submit" type="submit" value="Submit">
</form>
</div>
</body>
</html>
Answer
Solution:
html side: For checking on inputs like name and email, I suggest using the html attribute
required
on your input tags. And also, you can utilize the type of input likeemail
:required attribute in html checks during submission of form whether you have inputted a value. If there are no values, then a warning will prompt and tell you that it is required.
an email type in input tag validates whether the user input has proper format for the email.
php side: your sanitize method and validation have no problems, but if you are looking for the best implementation regarding form validation, I suggest using a function or better, add it in a form validator class. There is a simple example here of a good validator class: Easiest Form validation library for PHP
You can make your own class based on your preferences and of course you can experience the advantages of using oop design in your code.