Live check username availability using php and ajax

04/03/2017   03:31:30 PM

Hello, in this tutorial I will explain how to check live username availability.Username live availability is one of the most important things the database field, why because mostly we have to different kind of username and unique name for all users. Then only we can identify the individual user, so for here we are going to check the database field for already existing username availability.

1) Creating Database Table

First create a database then create table inside your database. I have created a sampledb database inside registration table created as you can see in the below image.

2) Create dbcontroller.php page

<?php
class DBController {
private $host = "localhost";
private $user = "root";
private $password = "";
private $database = "sampledb";
 
function __construct() {
$conn = $this->connectDB();
if(!empty($conn)) {
$this->selectDB($conn);
}
}
 
function connectDB() {
$conn = mysql_connect($this->host,$this->user,$this->password);
return $conn;
}
 
function selectDB($conn) {
mysql_select_db($this->database,$conn);
}
 
function runQuery($query) {
$result = mysql_query($query);
while($row=mysql_fetch_assoc($result)) {
$resultset[] = $row;
}
if(!empty($resultset))
return $resultset;
}
 
function numRows($query)
{
$result = mysql_query($query);
$rowcount = mysql_num_rows($result);
return $rowcount;
}
}
?>

 

3) Create index.php page

<style>
body{width:50%;}
#frmCheckUsername {border-top:#F0F0F0 2px solid;background:#FAF8F8;padding:10px;}
.demoInputBox{padding:7px; border:#F0F0F0 1px solid; border-radius:4px;}
.status-available{color:#2FC332;}
.status-not-available{color:#D60202;}
</style>
<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
<script>
function checkAvailability() {
$("#loaderIcon").show();
jQuery.ajax({
url: "check_user.php",
data:'username='+$("#username").val(),
type: "POST",
success:function(data)
{
$("#user-availability-status").html(data);
$("#loaderIcon").hide();
},
error:function (){}
});
}
</script>

 
<div id="frmCheckUsername">
<label>Check Username:</label>
<input name="username" type="text" id="username" class="demoInputBox" onBlur="checkAvailability()"><span id="user-availability-status"></span>
</div>
<p><img src="LoaderIcon.gif" id="loaderIcon" style="display:none" /></p>

 

4) Create check_user.php page

<?php
require_once("dbcontroller.php");
$db_handle = new DBController();
if(!empty($_POST["username"])) {
$result = mysql_query("SELECT count(*) FROM registration WHERE userName='" . $_POST["username"] . "'");
$row = mysql_fetch_row($result);
$user_count = $row[0];
if($user_count>0) {
echo "<span class='status-not-available'> Username Not Available.</span>";
}else{
echo "<span class='status-available'> Username Available.</span>";
}
}
?>

Output

                   

Support us by Sharing