Most common thing clients ask me to implement is to check if username that the user is trying to use during registration process is already taken.
This sounds complicated, but it really is not. jQuery will help us to achieve this functionality using very few lines of code.
I prefer AJAX approach as it is cool and users love it, as they know that username is free or taken even before they submit the actual form.
So let us create a table in mySQL to hold some user data:
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`username` varchar(150) NOT NULL,
`email` varchar(100) NOT NULL',
`pass` varchar(100) NOT NULL',
PRIMARY KEY (`id`)
)This is small and typical users table. Now let’s create a small form for our example:
<!-- Example markup -->
<form id="userForm">
<input type="text" id="username_box" name="user">
<button id="sub" type="submit">Check</button>
</form>
<div id="results" style="display:none;"></div>In real life application this would be a bigger form, but I want to concentrate only on important things and that is username field. As you noticed, I already added a div with id of “results” which will hold our result data.
Now some jQuery magic:
// jQuery version
$(function () {
$('#userForm').on('submit', function (e) {
e.preventDefault();
const $btn = $('#sub').prop('disabled', true);
const $res = $('#results').hide().empty();
const user = $.trim($('#username_box').val() || '');
if (!user) {
$res.text('Please enter a username.').show();
$btn.prop('disabled', false);
return;
}
$.ajax({
type: 'POST',
url: 'do_check.php',
data: { user }, // safer than building a query string
dataType: 'html',
success(html) {
$res.html(html).show();
},
error(xhr) {
$res.text(`Request failed: ${xhr.status} ${xhr.statusText}`).show();
},
complete() {
$btn.prop('disabled', false);
}
});
});
});
This jQuery code is making an AJAX call to PHP file do_check.php which is actually checking for username availability and return info about it. And here it is:
<?php
// do_check.php
// Only accept POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_POST['user'])) {
http_response_code(400);
exit('No username provided.');
}
$username = trim((string)$_POST['user']);
// Basic server-side validation (adjust to your policy)
if ($username === '' || !preg_match('/^[A-Za-z0-9_]{3,32}$/', $username)) {
http_response_code(422);
exit('Please enter a valid username (3–32 chars: letters, numbers, underscore).');
}
try {
// --- DB connection (replace with your credentials) ---
$pdo = new PDO(
'mysql:host=localhost;dbname=your_db;charset=utf8mb4',
'your_user',
'your_pass',
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]
);
// Case-insensitive check (depends on your collation; this works regardless)
$stmt = $pdo->prepare('SELECT COUNT(*) AS num FROM users WHERE LOWER(username) = LOWER(?)');
$stmt->execute([$username]);
$row = $stmt->fetch();
$safeUser = htmlspecialchars($username, ENT_QUOTES, 'UTF-8');
if (!empty($row) && (int)$row['num'] > 0) {
echo 'Username <em>' . $safeUser . '</em> is already taken!';
} else {
echo 'Username <em>' . $safeUser . '</em> is available!';
}
} catch (Throwable $e) {
// Don’t leak details to the client; log server-side if needed
http_response_code(500);
exit('Server error. Please try again later.');
}
Basically, code is checking in the database how many rows are in the users table with the username that we typed. If there are no such rows, the username is available.
The demo is available here
Sir i need a small module in php in which when user first register in the site , after submitting the form one folder automatically get created in that user table with same username that is if i register in the site say palti then after submitting the form palti’s folder must be there in the admin panel.
now what i want to do with this module is whenever the user want to upload any photographs for his relatives any where in the world all his uploaded pics will be available in his folder .
can you send me the source code? i having problem with the code you posted.
Thanks
Pingback: 10 Best Check Username Availability In PHP Using Ajax And JavaScript | ZoomZum
Pingback: 10 个用于检测用户名有效性的插件和JS脚本 - IT荟萃
sir How to make the same checking without pressing button “check”
To do the same without pressing the button “check” you would have to use keyup event handler instead of click.
And the events caught should be on input field.
So instead of
$("#sub").click(function() {you should use
$("#username_box").keyup(function() {Downside of this is that with every key pressed inside username field, you are checking the database if that username exists.
Thanks Zvonko, its too easy to do. and also easily i can connect it with database. Thanks a lot
Pingback: Some Useful Link For Web Developoer | Allah Hoo Akbar
Comments are closed.