简体   繁体   中英

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

I'm currently configuring my "User Registration" form in 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;

(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 AFTER the user clicks the " Submit " button.

I would have preferred Option A, of course. But, I was unsuccessful in my attempts to create a working AJAX/jQuery script.

So, I went with Option B instead.

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)

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?

(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() ??

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 :

      $(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);

(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

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(){ …

(c) Isn't there any way to actually insert that JQUERY into "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. 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 :

$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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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