MySQL – HTML Form Validation with PHP (filter_var)

You can validate that variable values look how they are supposed to by using filter_var in PHP. Filter_var determines if an email address, IP address, Int, Float, etc are formatted how they are supposed to be.

Validation Filters:



<form action="phpFormValidation.php" method="post">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="age"><br>
Email:<input type="text" name="email"><br>
<input type ="submit">




$name = $_POST['name'];
$age = $_POST['age'];
$email = $_POST['email'];

$servername = "localhost";
$username = "bob";
$password = "123456";
$db = "classDB";

$conn = new mysqli($servername, $username, $password, $db);

if ($conn->connect_error){
	die("Connection failed: ". $conn->connect_error);

if (filter_var($email,FILTER_VALIDATE_EMAIL) === FALSE) {
	print "Bad Email";

} elseif (filter_var($age,FILTER_VALIDATE_INT) === FALSE) {
	print "Bad Age";
} else {

$sql = "insert into emailSignup(name,age,email) values('$name','$age','$email')";

if ($conn->query($sql) === TRUE) {
	echo "ADDED: ".$name.", ".$age.", ".$email;
} else {
	echo "Error: ".$sql."<br>".$conn->error;


SQL for emailSignup

create table emailSignup(
	id int auto_increment primary key,
	name text,
	age int,
	email text);

Be the first to comment

Leave a Reply