Ketan Patel    26-Jun-2022

You might have seen that many websites check username availability in real time during the registration process. In this tutorial we will learn how to make a script to Check username availability using PHP and jQuery. 

Using this script you can check the username availability at run time. When users enter the username in the text field, the script will check if the entered username is available or not at runtime without submitting the form. 

Steps to follow

  • Database Table 
  • Database Connection
  • HTML Code
  • jQuery Code
  • PHP Code
  • Demo

Database Table
Here we are using the users table. You can have different table names as per your application convention. In order to create users table, run the below query:

CREATE TABLE `users` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `username` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

After creating the users table, run the below query in order to have some testing data for the demo purpose. You can add the sample data as per your choice.

INSERT INTO `users` (`id`, `username`, `email`, `password`) VALUES
(1, 'mark', 'mark@exmple.com', '$2a$12$v4afRs6juwEfTfsZNZcdm.fJK'),
(2, 'joy', 'joy@exmple.com', '$2a$12$VD2tpz3j/UgvRBSq8CiY1eK'),
(3, 'kevin', 'kevin@exmple.com', '$2a$12$kFBGwZsFl77fWGlVHy2zJ.W'),
(4, 'john', 'john@exmple.com', '$2a$12$KjjQG0aW.gvbhzVAARdDrOZ');

 

Database Connection
As we have the database table users with sample data ready, now we have to create a PHP file called connection.php for the database connection.

<?php

 $db_hostname = "localhost";
 $db_username = "root";
 $db_password = "password";
 $db_database = "username_availability";
 
// create connection
 $con = mysqli_connect($db_hostname, $db_username, $db_password , $db_database);

// check connection
if (!$con) {
   die("Connection failed: " . mysqli_connect_error());
}

 

HTML Code
Before creating our form, first we have to include the jQuery and Bootstrap libraries(as mentioned below) in the head section of the page. We will make ajax calls using jQuery and to provide styling to our form/fields we will use the bootstrap library.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.1.3/css/bootstrap.min.css" >

 

Create a simple form and add one input field for entering the username and create a <div id="username_availability_response"></div> in order to show the username availability response. 

Here, we have considered only a single field but in your real project you may have multiple fields in your form based on the requirements, you can simply use the logic of this script. Also, you can have your custom styling for the page and form.

<input type="text" name="username" id="username" class="form-control mb-2" autocomplete="off" placeholder="Enter Username" />
<div id="username_availability_response"></div>

 

jQuery Code
Now, we have to add jQuery code to handle the keyup event of the input field. 
So when keyup event trigger on username field, we will send ajax request with input field value as a data to the username_availability_checker.php file(we will create this file in next step) and will display the response in the div#username_availability_response section.

<script>
$(document).ready(function() {
   $("#username").keyup(function() {
      var username = $(this).val().trim();
      if (username != '') {
         $.ajax({
            url: 'username_availability_checker.php',
            type: 'post',
            data: { username: username },
            success: function(response) {
                $('#username_availability_response').html(response);
             }
         });
      } else {
         $("#username_availability_response").html("");
      }
    });
 });
</script>

 

PHP Code
Now create a new php file called username_availability_checker.php as we mentioned in the above jQuery code.  This file will check the entered username value against the database values and return the response based on the username availability.

<?php
 
include('connection.php'); 

if (isset($_POST['username']) && !empty($_POST['username'])) { 
    $username = mysqli_real_escape_string($con, trim($_POST['username']));
    $query    = "SELECT count(*) as usercount FROM `users` WHERE username = '".$username."'";
    $result   = mysqli_query($con, $query); 
    $row      = mysqli_fetch_array($result);

    if ($row['usercount'] == 0) {
        $response = '<span class="text-success">Username <b>'.$username.'</b> is available!</span>';
    } else {
        $response = '<span class="text-danger">Username <b>'.$username.'</b> is already taken!</span>';
    }

    echo $response;
    die;
}

?>

 

Let's combine the HTML and jquery code into a single file called index.php to see the complete code.

<!DOCTYPE html>
<html>
<head>
  <title>Check username availability using PHP and jQuery - PHP Dev Zone</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.1.3/css/bootstrap.min.css" >
</head>
<body class="container-fluid mt-3">
    <h4>Check username availability - <a href="https://www.php-dev-zone.com" target="_blank">PHP Dev Zone</a></h4>
    <div class="row mt-3">
        <div class="col-md-3">
            <input type="text" name="username" id="username" class="form-control mb-2" autocomplete="off" placeholder="Enter Username" />
            <div id="username_availability_response"></div>
        </div>
    </div>
    <script>
        $(document).ready(function() {
            $("#username").keyup(function() {
                var username = $(this).val().trim();
                if (username != '') {
                    $.ajax({
                        url: 'username_availability_checker.php',
                        type: 'post',
                        data: { username: username },
                        success: function(response) {
                            $('#username_availability_response').html(response);
                        }
                    });
                } else {
                    $("#username_availability_response").html("");
                }
            });
        });
    </script>
</body>
</html>

 

how to add custom field to Shopify cart page

Demo

Download Source Code

That’s it. We are done!
Thanks for reading.

About Ketan Patel

A Web Developer having 7+ years of experience in web development. Worked with Laravel-Lumen, CakePHP, CodeIgniter, Opencart to make sites for startup companies and small businesses. Apart from blogging, he likes to read Novels, Listening music and Net surfing.