lundi 4 juillet 2016

Preventing duplicate username entries when registering (PHP/MySQL

I have looked around and have seen many examples of it done but have unfortunately not been able to implement it into the code I am currently using.

I am wanting to prevent users from having the same username when they register on my page but the code I am using allows the entries to be the same.

How can I modify the below code to prevent this from happening?

 <?php
            require('db.php');
            // If form submitted, insert values into the database.
            if (isset($_POST['username'])){
                $username = $_POST['username'];
                $email = $_POST['email'];
                $password = $_POST['password'];
                $username = stripslashes($username);
                $username = mysql_real_escape_string($username);
                $email = stripslashes($email);
                $email = mysql_real_escape_string($email);
                $password = stripslashes($password);
                $password = mysql_real_escape_string($password);
                $trn_date = date("Y-m-d H:i:s");

                $res_login = $conn->query("select * from users where username='$username'");
                if($res_login -> num_rows > 0)
                {
                      echo "Username is already exists please try with another username";
                }
                else
                {
                      $query = "INSERT into `users` (username, password, email, trn_date) VALUES ('$username', '".md5($password)."', '$email', '$trn_date')";
                      $result = mysql_query($query);
                      if($result)
                      {
                                  echo "You are registered successfully.</h3><br/>Click here to <a href='login.php'>Login</a></div>";
                      }
                      else
                      {
                                  echo "error in registration";
                      }
                }
         }
        ?>

any help would be highly appreciated.

Aucun commentaire:

Enregistrer un commentaire