DEV Community

Cover image for Check If Email Address Is Already Exists in The Database
Code And Deploy
Code And Deploy

Posted on • Updated on

Check If Email Address Is Already Exists in The Database

Originally posted @ https://codeanddeploy.com visit and download the sample code: https://codeanddeploy.com/blog/php/check-if-email-address-is-already-exists-in-the-database

Advanced Laravel SAAS Starter Kit with CRUD Generator

Advanced Laravel SAAS Starter Kit with CRUD Generator - GET YOUR COPY NOW!

In this tutorial, you will learn how to check if email is already exists in the database using PHP & MySQL with Ajax. This task is needed if you are building applications in any programming language. You need to check if the email input is not yet existing in your database to prevent record duplication. But right now we will use PHP & MySQL for the sake of this tutorial.

check-if-email-address-is-already-exists-in-the-database

So first I will create a function so that it will be re-usable if I need to check email to a different table. Here is the function I coded under my functions.php file.



function isEmailExists($db, $tableName, $email)
{
        // SQL Statement
        $sql = "SELECT * FROM ".$tableName." WHERE email='".$email."'";

        // Process the query
        $results = $db->query($sql);

        // Fetch Associative array
        $row = $results->fetch_assoc();

        // Check if there is a result and response to  1 if email is existing
        return (is_array($row) && count($row)>0);
}


Enter fullscreen mode Exit fullscreen mode

Parameters:

$db - we need this for your SQL connection using mysqli object.

$tableName - we add the $tableName variable to put the table_name so that we can check any tables with possible checking of emails.

$email - your email string submitted from the form

Then next, we will call the function created above. Here is the code below for you to understand.



if(!isEmailValid($email)):
    $result['has_error'] = 1;
    $result['response'] = "Email address is invalid.";
elseif(isEmailExists($db, "employees", $email)):
    $result['has_error'] = 1;
    $result['response'] = "Email address is already exists.";
endif;


Enter fullscreen mode Exit fullscreen mode

So we have if statement above first we check if the email is invalid and next are about if the email exists.

So here is the complete source code for the save.php for you to understand deeper.



<?php
    // include config file
    require_once 'config.php';

    //a PHP Super Global variable which used to collect data after submitting it from the form
    $request = $_REQUEST;
    //get email address value
    $email = $request['email']; 
    //get first name value
    $first_name = $request['first_name'];
    //get last name value 
    $last_name = $request['last_name'];
    //get address value
    $address = $request['address'];

    // Defined $result as array
    $result = [];

    if(!isEmailValid($email)):
        $result['has_error'] = 1;
        $result['response'] = "Email address is invalid.";
    elseif(isEmailExists($db, "employees", $email)):
        $result['has_error'] = 1;
        $result['response'] = "Email address is already exists.";
    endif;

    // Check if no errors
    if(!count($result)):
        // SQL Statement
        $sql = "INSERT INTO employees (email, first_name, last_name, address)
        VALUES ('".$email."', '".$first_name."', '".$last_name."', '".$address."')";

        // Process the query
        if ($db->query($sql)) {
          $result['response'] = "Employee has been created.";
        } else {
          $result['response'] = "Error: " . $sql . "<br>" . $db->error;
        }

        // Close the connection after using it
        $db->close();
    endif;

    // Encode array into json format
    echo json_encode($result);


?>


Enter fullscreen mode Exit fullscreen mode

Then since we are using Ajax on this tutorial so here to code for the javascript inside scripts.js I call it save() function



function save() 
{
    $("#btnSubmit").on("click", function() {
        var $this           = $(this); //submit button selector using ID
        var $caption        = $this.html();// We store the html content of the submit button
        var form            = "#form"; //defined the #form ID
        var formData        = $(form).serializeArray(); //serialize the form into array
        var route           = $(form).attr('action'); //get the route using attribute action

        // Ajax config
        $.ajax({
            type: "POST", //we are using POST method to submit the data to the server side
            url: route, // get the route value
            data: formData, // our serialized array data for server side
            beforeSend: function () {//We add this before send to disable the button once we submit it so that we prevent the multiple click
                $this.attr('disabled', true).html("Processing...");
            },
            success: function (response) {//once the request successfully process to the server side it will return result here

                response = JSON.parse(response);

                // Check if there is has_error property on json response from the server
                if(!response.hasOwnProperty('has_error')) {
                    // Reload lists of employees
                    all();

                    // We will display the result using alert
                    Swal.fire({
                      icon: 'success',
                      title: 'Success.',
                      text: response.response
                    });

                    // Reset form
                    resetForm(form);
                } else {
                    // We will display the result using alert
                    Swal.fire({
                      icon: 'warning',
                      title: 'Error.',
                      text: response.response
                    });
                }

                $this.attr('disabled', false).html($caption);

            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                // You can put something here if there is an error from submitted request
            }
        });
    });
}


Enter fullscreen mode Exit fullscreen mode

So that's all, I hope you learn from it and apply it to your project. You can also download the full source code of this tutorial for you to see in action. Kindly visit here https://codeanddeploy.com/blog/php/check-if-email-address-is-already-exists-in-the-database if you want to download this code.

Advanced Laravel SAAS Starter Kit with CRUD Generator

Advanced Laravel SAAS Starter Kit with CRUD Generator - GET YOUR COPY NOW!

Thank you for reading. Happy Coding :)

Top comments (1)

Collapse
 
klnjmm profile image
Jimmy Klein

A little error in your isEmailValid function and you have a risk of SQL injection in your method isEmailExists !!

SELECT * FROM ".$tableName." WHERE email='".$email."';
Enter fullscreen mode Exit fullscreen mode

If you use mysqli extension, you have to use real_escape_string (or mysqli_real_escape_string), if you use PDO, use named parameter.

Example :

SELECT * FROM ".$tableName." WHERE email='".mysqli_real_escape_string($mysqli, $email)."';
Enter fullscreen mode Exit fullscreen mode