Create a database table
We will create a table named "users" in "test" database in MySQL. The table will have three columns - id, name and email. Email will be unique.
Create a form in Bootstrap 5
We will have a simple form with input fields Name and Email. You can add the Bootstrap 5 library from a CDN. The html code for this is given below:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Registration Form</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="style.css" rel="stylesheet">
</head>
<body>
<div class="container">
<h1>Registration Form</h1>
<form action="" method="post">
<div class="mb-3">
<label for="name" class="form-label fw-bold">Name</label>
<input type="text" class="form-control" name="name" id="name" placeholder="Enter Name"/>
<div class="text-danger"> </div>
</div>
<div class="mb-3">
<label for="email" class="form-label fw-bold">Email</label>
<input type="text" class="form-control" name="email" id="email" placeholder="Enter Email" />
<div class="text-danger"> </div>
</div>
<div class="text-center mt-3">
<button type="submit" name="submit" class="btn btn-primary">
Register
</button>
</div>
</div>
</body>
</html>
This is a simple form with two fields and a submit button. You can see that after each input, there is a place to display the validation error as below:
<div class="text-danger"> </div>
Our stylesheet is given below:
h1{
text-align: center;
}
form{
width: 50%;
margin: auto;
border: 1px solid #ddcccc;
padding: 14px;
border-radius: 10px;
background-color: #b0d9ec;
}
Write PHP code to add validation
When the form is submitted, we will start validating the inputs using PHP code.
After the form is submitted, we will get the values of the input fields into variables and also we will store the validation errors in some variables. Later, we will display them on the form. Once a validation fails, we will set a flag indicating that some validation failed.
Empty fields validation
We will check if the input values are empty by using the PHP empty() function.
<?php
$name = $email = "";
$nameErr = $emailErr = "";
$error = false;
if (isset($_POST['submit'])) {
$name = trim($_POST['name']);
$email = trim($_POST['email']);
if (empty($name)) {
$nameErr = "Name is Required";
$error = true;
}
if (empty($email)) {
$emailErr = "Email is Required";
$error = true;
}
if (!$error) {
// process the form data, insert the data
}
}
Note that the error flag is initialized as false and it is made true when a validation fails. At the end, we are checking if the error flag is false, which means all validations are successful, so that the form can be processed.
Email format validation
We will use the PHP function filter_var() to validate if the email format is correct. filter_var() returns true if the email format is correct by using a filter FILTER_VALIDATE_EMAIL. So, our email validation code will be as follows:
if (empty($email)) {
$emailErr = "Email is Required";
$error = true;
} else {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Email is Invalid";
$error = true;
}
}
Now, we will display values in the value attributes of the input fields and also display the validation error messages in the form.
<input type="text" class="form-control" name="name" id="name" placeholder="Enter Name" value="<?= $name ?>" />
<div class="text-danger"><?= $nameErr ?></div>
See the value attribute and the error message as displayed above. Same way, we can display them for the email field.
Unique email validation
We will check with the database table if the email already exists in the table. If exists, we will give message saying "Email already registered". We need to connect to a MySQL database first. We will add below code at the beginning:
// connect to the database
$conn = new mysqli("localhost", "root", "", "test");
if ($conn->connect_error) {
die("Database connection failed");
}
We are using "test" database in MySQL. we will select the data from "users" table for the given email id. If we find any row, we can say that the email is already registered. We will use prepared statements, see the below code:
// check for the unique validation
$sql = "select * from users where email = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
$emailErr = "Email is already registered";
$error = true;
}
Process the form after validations
When all the validations are successful, we will process the form data. We can insert the data into the database table. We will use exception handling using TRY-CATCH. See the code below:
if (!$error) {
// process the form data, insert the data
$sql = "insert into users (name, email) values (?,?)";
try {
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $name, $email);
$stmt->execute();
$succMsg = "Your are Registered";
} catch (Exception $e) {
$errMsg = $e->getMessage();
}
}
We are assigning success and error messages into variables. We will display them on the form after h1 heading:
<?php
if (!empty($succMsg)) { ?>
<div class="alert alert-success"><?= $succMsg ?></div>
<?php }
if (!empty($errMsg)) { ?>
<div class="alert alert-danger"><?= $errMsg ?></div>
<?php } ?>
Post a Comment