Check Availability of Username In Database Using PHP

If you want to check availability of username in database using PHP and Ajax with MySQL without submitting the form then this post is for you.

When we register on any website we have to select username which we want to keep so that next time when we login  we have to give the username and password, like in gmail, yahoo etc. we have to select email id which we want to keep but gmail or yahoo tell us by showing appropriate message the username is available or not, similarly when we want to create a registration form for our website we also give user to select username sometimes we take username as their email id but before registering we have to check that no one register with the same username or email id, so if we want to check username availability without submitting the form, we can do this using Ajax in PHP here i am giving you an example so that you can understand how you can do this.

Step1: Create database test_db
           create database test_db;
           Create table login
           create table login(username char(25));

Step2: Create a file index.php
<html>
<head>
    <title>Username Availability Check</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#name").keyup(function() {
var name = $('#name').val();
if(name=="")
{
$("#disp").html("");
}
else
{
$.ajax({
type: "POST",
url: "user_check.php",
data: "name="+ name ,
success: function(html){
$("#disp").html(html);
}
});
return false;
}
});
});
</script>
</head>
<body>
<div  style="width:400px;background-color: lightgray;">
    <br/>
<center><h3 style="color: green">Username Availability Check</h3>
<form method="post">
Username: <input type="text" name="name" id="name" /><br /><br />
<div id="disp"></div><br />
<input type="submit" name="submit" value="Submit" /><br/><br/>
<font style="color: red;">
<h3>Check Availability of Username in the database without submitting the form</h3>
</font>
</form>
    </center>
    <br/>
</div>
</body>
</html>

Step3: Create a file user_check.php
<?php
$query=mysql_connect("localhost","root","root");
mysql_select_db("test_db",$query);
if(isset($_POST['name']))
{
$name=mysql_real_escape_string($_POST['name']);
$query=mysql_query("select * from login where username='$name'");
$row=mysql_num_rows($query);
if($row==0)
{
echo "<span style='color:green;'>Available</span>";
}
else
{
echo "<span style='color:red;'>Already exist</span>";
}
}
?>

When user enter username in the text and it is not available in the database browser shows Available text in green color below the text box and if it is available in the database then browser shows Already Exist text with red color.
Output:

Check Availability of Username In Database Using PHP

Post a Comment

0 Comments