简体   繁体   中英

Check if username exists by php - and keep values

I'm trying to write a registration form, and when the user press the "submit" button, I want to check if the username already exists - and if so, to show a pop-up window that says "user name already exists - please change it". when the user closes that pop-up window using Javascript - I want the rest of the fields that the user inserts to stay in their place (I mean, only the username will be deleted - but the first name for example, will stay)

here's the code I wrote:

$con=mysqli_connect("localhost","root","","shnitzale");
        // Check connection
        if (mysqli_connect_errno())
          {
          echo "Failed to connect to MySQL: " . mysqli_connect_error();
          }

         $check="SELECT count (username) as num FROM registered_clients WHERE username=$_GET[User]";
         if (!mysqli_query($con, $check))
         {
             echo "Username already exist";
         }
         else
         {
             $sql="INSERT INTO registered_clients (Username, Password, First_name, Last_name,
                Day, Month, Year, Gender, Address, City, Phone_Number1, Phone_number2, Email)
                VALUES
                ('$_GET[User]','$_GET[Password]','$_GET[Fname]','$_GET[Lname]','$_GET[Day]',"
                     . "'$_GET[Month]','$_GET[Year]','$_GET[gender]','$_GET[Address]','$_GET[City]',"
                     . "'$_GET[Phone1]','$_GET[Phone2]','$_GET[Email]')";

             if (!mysqli_query($con,$sql))
             {
               die('Error: ' . mysqli_error($con));
             }

             echo "Thank you $_GET[Fname] $_GET[Lname]";
         }
            mysqli_close($con);

all of this is in a seperate php file that I go to after I press the "submit" button, I understand that I need to check the username validation before I get to this page, but I don't really know how... Thank you!

Your current username check isn't working due to this:

if (!mysqli_query($con, $check))
{
    echo "Username already exist";
}

This will never occur. Your current query will always return a valid result, even if no usernames are found. num will simply be 0.

Here's one way to do it:

$username = mysqli_real_escape_string($con, $_GET['User']); // Do some minimal sanitization at least!
$check = "SELECT username FROM registered_clients WHERE username='$username'";
$result = mysqli_query($con, $check);
if(mysqli_num_rows($result)) {
    echo "Username already exists";
}

This way you are pulling the actual usernames found, and counting them. Alternatively you could still use your count (username) as num query, but then you'd have to fetch the results of the query and look at the value of num .

Note that your INSERT query is still wide open to SQL injection. You need to sanitize all of those $_GET parameters before using them in your query.

You either need AJAX http://www.w3schools.com/ajax/ and check, if the username is available without loading another page or you can set the register form's action to the register page and insert all valid form data again.

Don't forget to sanitize your user data before!

If you want to do this with ajax: Create a seperate page (for now ill call it) usernamecheck.php

/*
    $database_connection = database connection and stuff
    Also, does your table have a primary key 'id'? I'd highly recommend it.
*/

$username = mysqli_real_escape_string($database_connection, $_GET['username']; // Use $_GET or $_POST depending on the AJAX request.
if (strlen($username) > 3){ // Only check if the username string is bigger than 4 characters. No point in checking an empty username.
    $UserCheck = mysqli_query("SELECT id FROM registered_clients WHERE username = '$username' LIMIT 1");
    if (mysqli_num_rows($UserCheck) > 0){
        die('<p style="color: red;">The username '.$username.' is already taken.</p>');
    } else {
        die('<p style="color: green;">The username '.$username.' is available.</p>');
    }
}

If you target your AJAX request to usernamecheck.php?username=superman and display the output of the page directly under the username field, the user would get a live update from the server.

You can also change the output of the script to a 1 or 0, so that you can pick it up in javascript.

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