Javascript 如何检查 USERNAME 是否已存在于 PHP/MYSQL 中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28535693/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if USERNAME already exists in PHP/MYSQL?
提问by newuserphp
I'm currently configuring my "User Registration" form in PHP.
我目前正在用 PHP 配置我的“用户注册”表单。
Trying to create a simple function to check if the username already exists in the database
尝试创建一个简单的函数来检查用户名是否已存在于数据库中
After doing my research, I have found that there are several ways this can be done.
经过我的研究,我发现有几种方法可以做到这一点。
(a) the best way is probably to use a PHP/AJAX combination, to check right away if the username already exists (in other words, the check is done BEFOREthe user clicks the "Submit" button;
(a) 最好的方法可能是使用 PHP/AJAX 组合,立即检查用户名是否已经存在(换句话说,检查是在用户点击“提交”按钮之前完成的;
(b) the other way is to do a simple SQL-query, which will return an error message, if that particular username already exists in the database. (The only drawback with this method is that : the check is done only AFTERthe user clicks the "Submit" button.
(b) 另一种方法是执行简单的 SQL 查询,如果该特定用户名已存在于数据库中,它将返回错误消息。(只有用这种方法的缺点是:只有在检查完成后,用户点击“提交”按钮。
I would have preferred Option A, of course. But, I was unsuccessful in my attempts to create a working AJAX/jQuery script.
当然,我更喜欢选项A。但是,我尝试创建一个有效的 AJAX/jQuery 脚本没有成功。
So, I went with Option B instead.
所以,我选择了选项 B。
And, I got it working.
而且,我让它工作了。
Here is the simply query I used :
这是我使用的简单查询:
if(isset($_POST['submit1'])||isset($_POST['submit1'])) {
$login = $_POST['login'];
$query_login = "SELECT login FROM registration WHERE login='$login';";
$result_login = mysqli_query($conn,$query_login);
$anything_found = mysqli_num_rows($result_login);
//check if the username already exists
if($anything_found>0)
{
echo "Sorry, that Username is already taken. Please choose another.";
return false; }
else { //proceed with registration
It worked fine. The error was displayed.
它工作得很好。显示错误。
The only problem is : the registration form itself disappeared.
唯一的问题是:注册表本身消失了。
I would have liked to display the error on the same page as the registration form, without having to RESET or somehow GO BACK.
我希望在与注册表单相同的页面上显示错误,而不必重置或以某种方式返回。
I know that the reason for this is something very minor (and kinda stupid on my part :D :D)
我知道这样做的原因是很小的(对我来说有点愚蠢:D:D)
Probably something to do with that "return false" thingy at the end of the query.
可能与查询结束时的“返回假”有关。
But, I am not sure.
但是,我不确定。
(a) How can I get the error message displayed on the form-page itself?
(a) 如何获得显示在表单页面上的错误消息?
(b) Or, better yet, is there a JavaScript Function I can use for this, so that I can simply call the function in the "Submit" button................like so : onSubmit = return function()??
(b) 或者,更好的是,是否有我可以使用的 JavaScript 函数,以便我可以简单地在“提交”按钮中调用该函数......就像所以: onSubmit = return function()??
Thanks
谢谢
UPDATE: Here is my form code.
更新:这是我的表单代码。
form action="myform.php" method="post">
<br>
Choose a username : <input type="text" name="login" value="<?=$login?>"
required>
UPDATE
更新
I was able to find the following jQuery code :
我能够找到以下 jQuery 代码:
$(document).ready(function() {
//the min chars for username
var min_chars = 3;
//result texts
var characters_error = 'Minimum amount of chars is 3';
var checking_html = 'Checking...';
//when button is clicked
$('#check_username_availability').click(function(){
//run the character number check
if($('#username').val().length < min_chars){
//if it's bellow the minimum show characters_error text '
$('#username_availability_result').html(characters_error);
}else{
//else show the cheking_text and run the function to check
$('#username_availability_result').html(checking_html);
check_availability();
}
});
});
//function to check username availability
function check_availability(){
//get the username
var username = $('#username').val();
//use ajax to run the check
$.post("check_username.php", { username: username },
function(result){
//if the result is 1
if(result == 1){
//show that the username is available
$('#username_availability_result').html(username + ' is
Available');
}else{
//show that the username is NOT available
$('#username_availability_result').html(username + ' is not
Available');
}
});
}
I assume that, for my particular example :
我假设,对于我的特定示例:
(a) the jQuery file cannot be inserted into the actual PHP file (my php file is named : registration.php, which includes both the html and php);
(a) jQuery 文件无法插入到实际的 PHP 文件中(我的 php 文件名为:registration.php,其中包含 html 和 php);
(b) this particular jQuery file includes a "button", which needs to be clicked to check if the username already exists. This is not a bad idea; but, I would rather that this was done automatically, without the need to click on a button (let's face it : there are some users out there who are indeed too clueless to perform this simple check manually). My aim is free the user as much as possible from the need to do such trivial tasks :D
(b) 这个特定的 jQuery 文件包含一个“按钮”,需要点击它来检查用户名是否已经存在。这不是一个坏主意。但是,我宁愿这是自动完成的,而无需单击按钮(让我们面对现实:有些用户确实太无知而无法手动执行此简单检查)。我的目标是尽可能让用户免于执行此类琐碎任务的需要:D
Anyway, my point is : so as to eliminate the need for a button, I would like to include an auto-function which checks once the user types in the username.
无论如何,我的观点是:为了消除对按钮的需要,我想包含一个自动功能,一旦用户输入用户名,就会进行检查。
According to Google, the following function is what I need :
根据谷歌的说法,我需要以下功能:
Replace $(‘#check_username_availability').click(function(){… with $(‘#username').keyup(function(){ …
将$('#check_username_availability').click(function(){... 替换为 $('#username').keyup(function(){ ...
(c) Isn't there any way to actually insertthat JQUERY into "registration.php" ?? Or, should it be a separate file entirely?
(c) 有没有办法将JQUERY实际插入到“registration.php”中??或者,它应该完全是一个单独的文件吗?
回答by IBAD GORE
The better way would be you bind the ".blur" event on which you may check if the username is valid via ajax. Don't forget to check the username after form submission at before form submission. Below your input box create a
更好的方法是绑定“.blur”事件,您可以通过 ajax 检查用户名是否有效。不要忘记在表单提交后在表单提交之前检查用户名。在您的输入框下方创建一个
<span class= "error">Username is already present. </span>
<span class= "success">Username can be assigned. </span>
and just display the message accordingly.
并相应地显示消息。
You may use the script as
您可以将脚本用作
$.ajax({
url : "check_username.php",// your username checker url
type : "POST",
data : {"username",$("input.username").val()},
success : function (data)
{
if(data == "success")
{$(".success").show();$(".error").hide();}
else
{$(".error").show();$(".success").hide();}
},
});
You php code would be something like this :
你的 php 代码是这样的:
$query = "SELECT username FROM tab_users WHERE username = '".$_POST['username']."'";
$result_login = mysqli_query($conn,$query_login);
$anything_found = mysqli_num_rows($result_login);
//check if the username already exists
if($anything_found>0)
{
echo "fail";
return false;
}
else
{
echo "success";
return false;
}
回答by racuevji
You can disable the submit button and add a span message near the input field.
您可以禁用提交按钮并在输入字段附近添加跨度消息。
Check this code:
检查此代码:
function checkUsername()
{
var username = document.getElementById('username');
var message = document.getElementById('confirmUsername');
/*This is just to see how it works, remove this lines*/
message.innerHTML = username.value;
document.getElementById("send").disabled = true;
/*********************************************/
$.ajax({
url : "check_username.php",// your username checker url
type : "POST",
data : {username: username},
success: function (response) {
if (response==0)
{
message.innerHTML = "Valid Username";
document.getElementById("send").disabled = false;
}
if (response==1)
{
message.innerHTML = "Already Used";
document.getElementById("send").disabled = true;
}
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<label for="uername">Username:</label>
<input type="text" class="form-control" name="username" id="username" onkeyup="checkUsername(); return false;" required/>
<span id="confirmUsername" class="confirmUsername"></span>
<button type="submit" id="send" name="action" value="Send">Send</button>
回答by Jodi ivan Lumbantoruan
put this
把这个
include([your validating php file]);
include([your validating php file]);
and in your form action link to your login form file.
并在您的表单操作中链接到您的登录表单文件。
note: your login file have to be php file.
注意:您的登录文件必须是 php 文件。

