How to prevent duplicate usernames when people reg

2019-02-14 05:27发布

I have been making a login/register system and I am drawing close to finishing my register portion of code. The only problem I am running into is how to make it so that users cannot register with duplicated usernames. I want it to work so that my database wont accept the information, and it will tell the user about the error. Any help is appreciated.

My PHP

<?php
include ('database_connection.php');
if (isset($_POST['formsubmitted'])) {
$error = array();//Declare An Array to store any error message  
if (empty($_POST['name'])) {//if no name has been supplied 
    $error[] = 'Please Enter a name ';//add to array "error"
} else {
    $name = $_POST['name'];//else assign it a variable
}

if (empty($_POST['e-mail'])) {
    $error[] = 'Please Enter your Email ';
} else {


    if (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $_POST['e-mail'])) {
       //regular expression for email validation
        $Email = $_POST['e-mail'];
    } else {
         $error[] = 'Your EMail Address is invalid  ';
    }


}


if (empty($_POST['Password'])) {
    $error[] = 'Please Enter Your Password ';
} else {
    $Password = $_POST['Password'];
}


if (empty($error)) //send to Database if there's no error '

6条回答
仙女界的扛把子
2楼-- · 2019-02-14 05:38

I used a PDO and class method, may be of some use.

//function for checking if the user already exists in the database
 public function userExists($username){

//prepared statements for added security
$query = $this->db->prepare("SELECT COUNT(`id`) FROM `users` WHERE `username`= ?");
$query->bindValue(1, $username);

try{
    //execute the query
    $query->execute();
    $rows = $query->fetchColumn();

    //if a row is returned...user already exists
    if($rows == 1){
        return true;
    }else{
        return false;
    }
//catch the exception
}catch (PDOException $e){
    die($e->getMessage());
}
 }//end function userExists

note the prepared statements too - definitely the way forward

查看更多
看我几分像从前
3楼-- · 2019-02-14 05:41

you can do like this :

<?php

 //---put this code before "if (empty($error))"------

 $username = $_POST['username'];
 //---if your table user is "table_user" and fieldname username is "username"
 $query = 'SELECT username FROM table_user WHERE username = "' . $username . '" LIMIT 1';
 $result  = mysql_query($query)
 $totalNumRowResult = mysql_num_rows($result);

 if($totalNumRowResult > 0) {
  $error[] = 'User exist';
 }

?>

Hope that helps.

查看更多
ら.Afraid
4楼-- · 2019-02-14 05:46

You can do it like this when the user post the username for example and click submit you can write this code or add it to your code with your modification :

<?php
$connect = mysql_connect('whatever','whatever','whatever');
$database = mysql_select_db('your dbname');
$username = $_POST['username'];
if(isset($username)){
$mysql_get_users = mysql_query("SELECT * FROM table_name where username='$username'");

$get_rows = mysql_affected_rows($connect);

if($get_rows >=1){
echo "user exists";
die();
}

else{
echo "user do not exists";
}



}
?>
查看更多
手持菜刀,她持情操
5楼-- · 2019-02-14 05:47

You have to (can) make condition that forbids registration if username already exists.

    $sql="SELECT username FROM tablename WHERE username='".$username."'";//looking through existing usernames
    $resul=mysql_query($sql);
    $num = mysql_num_rows($resul);

    if ($num !=0){ //If there is already such username...

    die("There is user with that username.");  // ...kill the script!
} else //continue with the script
查看更多
仙女界的扛把子
6楼-- · 2019-02-14 05:54

There are two things you should do.

  1. Make the user name a primary key in the database table. This is easily done using phpmyadmin.

  2. Validate prior to insert.

For the second step, here's an algorithm. You may implement it in your own way using pdo, mysqli or even mysql (although it's not recommended now).

Algorithm at the end of your code (i.e., if there aren't errors)...

Select records that match the USERNAME supplied in the post.

If it exists, give out an error.

If it doesn't exist, insert it.

Hope that helps.

查看更多
做个烂人
7楼-- · 2019-02-14 05:56

I think something like this is what you're looking for:

if (isset($_POST['user']))
{
    $user = $_POST['user'];

    if (mysql_num_rows(yourFunctionForQueryingMySQL("SELECT * FROM tablename WHERE user='$user'")))
            echo "Name is taken";
    else echo "Name available";
}
查看更多
登录 后发表回答