duanli0162
duanli0162
2015-02-05 23:08
浏览 17
已采纳

试图阻止创建重复用户

I cannot for the life of me find out what is wrong with this. It is probably some hidden rule or silly mistake. This code is meant to prevent users from creating the same user or same email twice but only works for the username. Am I missing something or is it just a silly mistake? I am using two if statements to try and achieve this (as noted by comments) but it is not working.

Thanks in advance

$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['emailAddress'];


// Create connection
$conn = new mysqli($servername, $SQLusername, $SQLpassword, $DBname);

// Check connection
if (!$conn) {
    die("Connection failed: " . mysql_connect_error());
}

$sql = "SELECT * FROM `Login` WHERE `Username` LIKE '$username' AND `Password` LIKE '$password';";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);

$emailDB = $row['Email'];
$usernameDB = $row['Username'];

// username validation
if ($username == $usernameDB)
{
    echo "Username '$username' is already taken!<br>";
    exit;
}
//E-mail validation
if ($email == $emailDB)
{
    echo "Email '$email' is already registered!<br>";
    exit;
}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dounao2829
    dounao2829 2015-02-05 23:20
    已采纳

    You just need another query :))) :

    $sql = "SELECT * FROM `Login` 
           WHERE `Username` LIKE '$username' 
           OR `Email` LIKE '$email';";
    $result = mysqli_query($conn, $sql);
    $row = mysqli_fetch_assoc($result);
    
    $emailDB = $row['Email'];
    $usernameDB = $row['Username'];
    
    // username validation
    if ($username == $usernameDB)
    {
        echo "Username '$username' is already taken!<br>";
        exit;
    }
    //E-mail validation
    if ($email == $emailDB)
    {
        echo "Email '$email' is already registered!<br>";
        exit;
    }
    

    and you should better use:

    "SELECT * FROM `Login` 
               WHERE `Username` = '$username' 
               OR `Email` = '$email';"
    

    because if it not really equal, new user can be registered :-)

    点赞 评论

相关推荐