Ajax Username Validation with PHP and MySQL

Tutorial for ajax username validation using jquery and php to check if the username is available in the mysql database.

Ajax username validation with php and mysql

Requirements

Database and table

First create a database in mysql and create a table called members in it.


CREATE DATABASE books;
CREATE TABLE members (id INT(20) NOT NULL AUTO_INCREMENT, username VARCHAR(100));

Insert some dummy values.


INSERT INTO members (username) VALUES("anand.roshan");
...

Example

members table in mysql

HTML Markup


<input type="text" name="username" id="username" placeholder="Enter Username">
<div id="availability"></div>

We need a text input box and a div to show the result, with suitable ids.

jQuery


$(document).ready(function () {
 $("#username").blur(function () {
 var username = $(this).val();
 if (username == '') {
 $("#availability").html("");
 }else{
 $.ajax({
 url: "validation.php?uname="+username
 }).done(function( data ) {
 $("#availability").html(data);
 }); 
 } 
 });
});

After including the jQuery library insert the above code inside of your head tag

We used a function called .blur()

Whenever the input box with the id of “username” looses its focus, the jQuery code will send an ajax request to validation.php.

For this tutorial, we’ve used GET method but you can use POST method as well.

validation.php


<?php
$db_user = "YOUR_DB_USER";
$db_password = "YOUR_DB_PASSWORD";
$db_name = "YOUR_DB_NAME";
$db_host = "YOUR_DB_HOST";

//connecting to mysql database
$con = new mysqli($db_host, $db_user, $db_password, $db_name);

//prints error message if connection is not successful
if ($con -> connect_error > 0) {
 die('Unable to connect to database [' . $con -> connect_error . ']');
}

//Gets username value from the URL
$uname = $_GET['uname'];

//Checks if the username is available or not
$query = "SELECT username FROM members WHERE username = '$uname'";

$result = mysqli_query($con, $query);

//Prints the result
if (mysqli_num_rows($result)<1) {
 echo "<span class='green'>Available</span>";
}
else{
 echo "<span class='red'>Not available</span>";
}
?>

Basically it sends the username to validation.php if it is not empty

We are trying to select the username from members table where the username is equal to the value entered in text box.

If the result returns one or more rows, then the username is not available otherwise it is availabe.

Now give a nice style to the classes green and red with the help of CSS

That’s it. Keep sharing the post and keep scrolled with us for more updates.


Anand Roshan

Author: Anand Roshan

An entrepreneur, programmer and a passionate artist who loves to work independently. Get social: Twitter | Google + | Artist Page

3 comments on “Ajax Username Validation with PHP and MySQL”

Leave a Reply

Your email address will not be published. Required fields are marked *