Unique Email Validation in a Registration Form in PHP and MySQL

Unique email validation is an essential feature in any user registration form built with PHP and MySQL. It prevents duplicate emails and improves your website's user management, enhancing data accuracy. In this tutorial, you'll learn how to check whether an email already exists in the MySQL database before registration. Using simple PHP and SQL queries, you can implement server-side validation to prevent duplicate email submissions. You will also learn how to handle form input validation in PHP and display custom validation error messages.

We will use a simple form in Bootstrap 5 with just name and email fields and validate the form using PHP after the form is submitted. So, this will be server-side form validation with PHP and MySQL. We will work on these validations:

  1. Required fields validation
  2. Email format validation
  3. Unique email validation

If all validations are successful, we will insert the form data into a database table.

Below is the screenshot of the Form

Form Validation in PHP

A registration form can have many other fields, but for our example we are using only two fields here Name and Email as our focus in on Email validation.

Watch YouTube Video

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.

Email Validation in PHP

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 } ?>

ajax dropdown selected value in phpTest the Application

Before testing, make sure Apache and MySQL services are running in the XAMPP Control panel and the database table is created in test database. In the browser, run index.php. You will see that the form is displayed. Test for required fields and also test for the invalid email format. If you enter valid values for the name and email, the form will be submitted and a row will be inserted in the database table. Now, try to register another user with the same email id which is alerady registered. You should see the error message as the same email is already registered.

PHP form validation source codeDownload Source Code

You can download the source code from GitHub by clicking on the download button below:

Conclusion

In this PHP tutorial, we have learned how to validate a form using PHP and MySQL. We validated empty fields, email format and unique email in a registration form.

Please write your comments/questions in the Comments section below. Your questions, doubts and suggestions are always welcome.

Post a Comment

Save my Name and Email id for future comments