Written by Sai Sandeep Thota on June 14, 2015 in php > Programming

Check Username Availability using PHP and jQuery

GET ALERTS:

Get our Latest updates delivered to your mailbox!

When you have a user registration form, you need to prevent duplicate usernames. In this tutorial we will be providing a sample code for Checking username availability using PHP and jQuery. As two users cannot have the same username, during registration process of the user we need check whether the requested username is available or not. If it is available the user can continue registration process else they need to choose another username. It would be easy for the user when we check the availability of username in the registration page itself instead of throwing an error after filling all the details.

Check_Username_Availability

The process flow is, User enters registration page and gives the input of the desired username and clicks on check availability – this triggers Click event and checks if the desired Username exists in the Database. If it exists, then an error is thrown.

DemoDownload Source Code

Register.php

<html>
<body>
<table border="0">
	<form method="POST" action="register.php" id="regform">
		<tr>
			<td colspan="2">Password will be sent via Email.</td>
		</tr>
		
		<tr>
			<td>Username:</td>
			<td><input type="text" placeholder="Username" id="username"><a id="checkavail">Check Availability</a></td>
		</tr>

		<tr>
			<td>Email:</td>
			<td><input type="email" placeholder="Email" id="email"></td>
		</tr>
		<tr>
			<td colspan="2"><input type="submit" id="sign" value="Register"></td>
		</tr>
	</form>
</table>
<script src="jquery-2.1.3.min.js"></script>
<script src="CheckUser.js"></script>
</body>
</html>

CheckUser.js

$(function(){
	$("#checkavail").click(function(){
		var uname = $("#username").val();
		$.ajax({
		  type: "POST",
		  url: 'check.php',
		  data: {uname:uname},
		  success: function(d){
		  	if(d==-1){
		  		$('#username').css("border", "1px solid red");
		  		$('#username').focus();
		  		$("#message").toggle();
		  		$("#sign").attr('disabled', 'disabled');
		  		$("#regform").submit(function(e){
		  			e.preventDefault();
		  		});
		  	}
		  	if(d==1){
		  		$('#username').css("border", "1px solid green");
		  		$('#message').css('display', 'none');
		  		$('#sign').removeAttr('disabled');
		  	}
		  }
		});
		
	});
});

check.php

<?php
//Check.php file contains SQL query to check availability of username 
//in the Database
$mysqli = mysqli_connect("localhost","root","my_password","my_db");

$check = $_POST['uname'];

$sql = "SELECT username FROM users WHERE username='$check'";
$records = $mysqli->query($sql);

$recCount = $records->num_rows;

if($recCount>0) {
	echo -1;
}

else {
	echo 1;
}

?>

If you have any queries, please let us know them in the comments section.

{ 0 comments… add one now }

Leave a Comment

Previous post:

Next post: