简体   繁体   中英

MySQL - Check if username already exists before submitting the form

I am trying to check if a username exists or not before the form that will trigger the insertion of a new username is submitted, so that I can notify the user of the availability (or not) of the username she has selected.

But my code doesn't works. Where is the problem? Here is my code:

<?php
$servername = "localhost";
$username = "zprestau01u";
$password = "ZPrestau#01U$100";
$dbname = "zprestau01";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$username=$_POST['Name'];
$email = $_POST['Email'];
$password = $_POST['Password'];

//Query statement with placeholder
$query = "SELECT Name
          FROM demotable 
          WHERE demotable.Name = '$username'";

//Put the parameters in an array
$params = array($username);

//Execute it
try {
    $stmt = $conn->prepare($query);
    $result = $stmt->execute($params);
} catch(PDOException $ex) {
    echo $ex->getMessage());
}

//Now Check for the row count
if($stmt->rowCount > 0) {
    echo "Account Exists";
} else{
                $sql = "INSERT INTO demotable(Name,Email,Password) VALUES ('$username','$email','$password')";

                if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}
            }

$conn->close();
?>

NB: At the same time I am trying to insert username in MySQL if it is not existed.

The first thing is to add a security layer at a database level, to prevent the insertion of duplicated usernames. Assuming Name column corresponds to username, you need to configure your SQL database to understand Name as a unique key:

ALTER TABLE Demotable ADD UNIQUE (Name);

In this way, if you try to insert a row with an existing name, an exception will be created and the row with the duplicated username will not be inserted.

Checking before the form is submitted is a nice improvement on top of that. If you're trying to check the availability of a username before the form is submitted, for UX and user information purposes, then a good solution may be to use AJAX integrated within your PHP code. There is a nice explanation elsewhere that you may want to check.

Though a lot of code is provided, you may pay special attention to the actual AJAX query and adapt it to your needs and those of your project. Using jQuery to make the ajax call it would look like this:

<script>
$(document).ready(function(){

   $("#txt_uname").keyup(function(){

      var uname = $("#txt_uname").val().trim();

      if(uname != ''){

         $("#uname_response").show();

         $.ajax({
            url: 'uname_check.php',
            type: 'post',
            data: {uname:uname},
            success: function(response){

                if(response > 0){
                    $("#uname_response").html("<span class='not-exists'>* Username Already in use.</span>");
                }else{
                    $("#uname_response").html("<span class='exists'>Available.</span>");
                }

             }
          });
      }else{
         $("#uname_response").hide();
      }

    });

 });
</script>

If you want to check before submitting the form you can go for ajax only.check after click the submit button this will work you can try this out.

<?php
    $servername = "xxxxxxxxx";
    $username = "xxxxxxxxxx";
    $password = "";
    $dbname = "test";
    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);

    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    if(isset($_POST['submit'])) {
        $username=$_POST['username'];
        $email = $_POST['email'];
        $password = $_POST['password'];

        //Query statement with placeholder
        $query = "SELECT fname
                  FROM person
                  WHERE fname = '$username'";

        // Execute it
        try {
            $stmt = $conn->prepare($query);
            //for you no need to pass parameter inside execute statement
            $result = $stmt->execute();
            //After executing the query store the result like below
            $stmt->store_result();
        } catch(PDOException $ex) {
            echo $ex->getMessage();
        }

        //Now Check for the row count
       //you have to check numrows >0 like this
       if($stmt->num_rows>0) {
           echo "Account Exists";
           die;
       } else {
           $sql = "INSERT INTO person(username,email,password) VALUES ('$username','$email','$password')";

          if ($conn->query($sql) === TRUE) {
             echo "New record created successfully";
          } else {
             echo "Error: " . $sql . "<br>" . $conn->error;
          }
      }
   }
   $conn->close();
?>

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