How to generate random username using PHP, Ajax, and MySQL
In this tutorial we are going to learn how to generate unique or random username using php and jquery ajax. just follow the below step to generate unique username in php. You may also like How to Check UserName and Email Availability From Database using PHP and Ajax and How to Remote call using bootstrap validator.
HTML and jQuery Code
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
function get_username()
{
var name=$("#name").val();
if(name!="")
{
$.ajax
({
type:'post',
url:'getusername.php',
data:{
get_username:name
},
success:function(response)
{
$("#username").css({"display":"block"});
$("#username").html("UserName : "+response);
$("#username_value").val(response);
}
});
}
}
</script>
</head>
<body>
<form method="post"action="getusername.php">
<input type="text" name="name" id="name" placeholder="Enter Name" onblur="get_username();">
<p id="username"></p>
<input type="text" name="email" placeholder="Enter Email">
<br>
<input type="password" name="pass" placeholder="**********">
<input type="hidden" name="username_value" id="username_value">
<br>
<input type="submit" name="signup" value="Do SignUp">
</form>
</body>
</html>
PHP Code (getusername.php)
<?php
if (isset($_POST['get_username'])) {
$user_name = str_replace(' ', '', $_POST['get_username']);
random_username($user_name);
exit();
}
function random_username($user_name) {
$new_name = $user_name . mt_rand(0, 10000);
check_user_name($new_name, $user_name);
}
function check_user_name($new_name, $user_name) {
$select = mysql_query("select * from users where username='$new_name'");
if (mysql_num_rows($select)) {
random_username($user_name);
} else {
echo $new_name;
}
}
if (isset($_POST['signup'])) {
$name = $_POST['name'];
$username = $_POST['username_value'];
$email = $_POST['email'];
$pass = $_POST['pass'];
mysql_query("insert into users values('','$name','$username','$email','$pass')");
}
?>
Leave a Reply