0

After following replies to a previous question on here, I used jQuery to return whether a username was available or not, I found some code on a site, which showed me how to do it. From what I can see, the code seems to be structured correctly, and is connecting to the Database, however even if the name isn't in the Database it returns that it is not Available.

Here is the jQuery(And Registration form) which is included in the register.php file (Will link below jQuery).

<div class="registration">
  <h3>Register - Create a new Account</h3>

  <form action="confirm-registration.php" method="POST">
    <input type="text" name="create-username" id="username" placeholder="Username" maxlength="25" /><input type='button' id='check_username_availability' value='Check Availability'>
<div id='username_availability_result'></div>  <br />
    <input type="password" name="create-password" placeholder="Password" /> <br />
    <input type="password" name="confirm-password" placeholder="Confirm Password" /> <br />
    <input type="email" name="create-email" placeholder="E-mail Address" maxlength="45" /> <br />
    <input type="submit" value="Complete Registration" />
  </form>

  <form>
    <input type="submit" value="Cancel" />
  </form>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyCJnj2nWoM86eU8Bq2G4lSNz3udIkZT4YY&sensor=false"></script>
  <script type="text/javascript" src="/check-user.js"></script>
<script type="text/javascript">
$(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 > 0){
                    //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');
                }
        });

}
</script>

The code below links in the final file relevant to this - check-username.php. This is the file that queries the database with the username and then returns it. I will link that below this php.

<?php
    include '../connect.php';

    if (isset($_SESSION['signed_in']) && $_SESSION['signed_in'] == true ) {
      header('Location : http://localhost/blog');
    } else {
      echo include 'registration_form.php';
      require 'check_username.php';
    }
 ?>
<?php
    $username = mysql_real_escape_string(isset($_POST['create-username']));

    //mysql query to select field username if it's equal to the username that we check '
    $result = mysql_query('SELECT user_name from users where user_name = "'. $username .'"');

    //if number of rows fields is bigger them 0 that means it's NOT available '
    if(mysql_num_rows($result) > 0){
      //and we send 0 to the ajax request
      echo 0;
    } else {
      //else if it's not bigger then 0, then it's available '
      //and we send 1 to the ajax request
      echo 1;
    }

Any help with this would be appreciated, this isn't my code and I've not done much jQuery, so after trying a few things I'm now at a complete loss on how to fix it.

Thanks, Ben

BenJ30
  • 86
  • 1
  • 8

4 Answers4

1

This isn't doing what you think:

$username = mysql_real_escape_string(isset($_POST['create-username']));

The result here is going to be something like:

$username = 'true';

Because isset() returns a boolean. You can check if something is set:

if (!isset($_POST['create-username'])) {
    // show an error, stop processing the page
}

But to get the actual value, isset() isn't what you want:

$username = mysql_real_escape_string($_POST['create-username']);

This way you're checking the user input value, and not a boolean value. (It's weird that there's a 'true', or whatever that evaluates to, username in your data. Possibly from another similar error elsewhere, though.)


As a side note, even though you're using mysql_real_escape_string(), you should still investigate upgrading to something like mysqli and using prepared statements with query parameters.

Additional side note: Currently your username comparison is case-sensitive. So 'David' and 'david' would be considered different users. If that's not what you want, you might want to standardize on a casing. Either store the user-input unmodified username and make it upper-/lower-case for comparison, or make it upper-/lower-case before storing and always do the same for other inputs.

David
  • 208,112
  • 36
  • 198
  • 279
  • I removed isset() and now I can undefined index, I read that adding isset would solve such an issue on a question on this site. I'm not really sure on how I would get it to work. – BenJ30 Oct 21 '15 at 21:26
  • @BenJ30: You'd use `isset()` similar to how I show in an `if` block in this answer. It's used to check if the value exists before trying to use the value. But it's not used to actually retrieve the value. – David Oct 21 '15 at 21:26
  • I messed up my reply to that comment, what I was meant to say is. I removed the isset as you said and now it returns the error: Notice: Undefined index: username in C:\xampp\htdocs\blog\user\check_username.php on line 2 - I changed it to username due to a reply further down on this answer about the ajax name. However even with it as create-username, I get the same error. – BenJ30 Oct 21 '15 at 21:48
  • @BenJ30: When you debug this, is the `username` value present when posting to the server? Examine the POST request being made in your browser's debugging tools which produces that error, see what's included in the request. – David Oct 21 '15 at 21:50
  • Uhmmm, I'm not sure what you mean. How would I go about doing this, sorry about being difficult as well. I'm fairly new to PHP, so really doing some trial-by-error. – BenJ30 Oct 21 '15 at 22:01
  • @BenJ30: Your browser should have debugging tools available which can be used to examine (among other things) the network requests sent by a page. This will allow you to see the POST request being made in the AJAX call as well as the server's response to that request. If `$_POST['username']` is telling you that it's an undefined index, then presumably it's not actually being sent in the POST request. – David Oct 21 '15 at 22:04
  • I've looked around at it. I'm still not 100% about what you mean. I can see that under the header General the Request Method is set to GET. I'm not sure if this is relevant to what you are talking about. – BenJ30 Oct 21 '15 at 22:11
  • @BenJ30: This format isn't really conducive to helping you with debugging. But you may find some helpful information on this error here: http://stackoverflow.com/questions/4261133/php-notice-undefined-variable-and-notice-undefined-index Basically your code needs to check if a client-input value is set before trying to use it, and your overall page/AJAX flow needs to send the right values to the right places. I can't see the big picture of your overall project from where I am, though. – David Oct 21 '15 at 22:15
1

In addition to what has already been mentioned:

In your jQuery, you are using:

$.post("check_username.php", { username: username }...)

which would post "bob" => "bob" as a key/value pair.

Try it like this:

{ "username": username }

Additionally, your PHP is checking for:

$_POST['create-username']

while it should be:

$_POST['username'] 

(should match what you $.post from Ajax)


Use Chromes network console to monitor the request and make sure you are getting the expected results.
Michael Doye
  • 8,063
  • 5
  • 40
  • 56
0

You need to normalize your comparison in SQL. See the LOWER() mysql function and strtolower php function. I'd also add a trim() for good measure.

$result = mysql_query('SELECT user_name from users where LOWER(user_name) = "'. strtolower(trim($username)) .'"');

Additionally, you can cut the 5 line if logic at the bottom to one line by just echoing out the echo mysql_num_rows(result);

And yes that isset() should come out.

Andrew Coder
  • 1,058
  • 7
  • 13
  • $username = mysql_real_escape_string(isset($_POST['create-username'])); what is isset doing here : try to remove isset – yarek Oct 21 '15 at 20:55
  • Yarek is correct, this would pass true or false to the SQL statement instead of the username. (based on nesting) – Andrew Coder Oct 21 '15 at 20:57
  • I removed isset as said above, as well as in David's post and now I get an Undefined index. – BenJ30 Oct 21 '15 at 21:39
-1

$username = mysql_real_escape_string(isset($_POST['create-username']));

$username is taking a wrong value beacause of the isset function: try to remove it.

yarek
  • 11,278
  • 30
  • 120
  • 219