简体   繁体   English

如何检查USERNAME在PHP / MYSQL中是否已经存在?

[英]How to check if USERNAME already exists in PHP/MYSQL?

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 BEFORE the 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. (b)另一种方法是执行简单的SQL查询,如果数据库中已经存在该特定的用户名,则该查询将返回错误消息。 (The only drawback with this method is that : the check is done only AFTER the user clicks the " Submit " button. (这种方法的唯一缺点是:只有用户点击“ 提交 ”按钮,检查完成。

I would have preferred Option A, of course. 当然,我会选择选项A。 But, I was unsuccessful in my attempts to create a working AJAX/jQuery script. 但是,我尝试创建一个有效的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. 在查询结束时可能与“ return false ”问题有关。

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 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. (b)这个特定的jQuery文件包含一个“按钮”,需要单击该按钮以检查用户名是否已存在。 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 我的目标是让用户尽可能地摆脱琐碎的工作: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 insert that JQUERY into "registration.php" ?? (c)没有任何方法可以将该JQUERY实际插入 “ registration.php”中? Or, should it be a separate file entirely? 还是应该完全是一个单独的文件?

The better way would be you bind the ".blur" event on which you may check if the username is valid via ajax. 更好的方法是绑定“ .blur”事件,您可以在该事件上通过ajax检查用户名是否有效。 Don't forget to check the username after form submission at before form submission. 提交表单后,别忘了在提交表单后检查用户名。 Below your input box create a 在您的输入框下方,创建一个

<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;    
}

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> 

put this 把这个

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文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM