试图阻止创建重复用户

时间:2015-02-05 23:08:54

标签: php validation if-statement login mysqli

我不能为我的生活找出这个问题。这可能是一些隐藏的规则或愚蠢的错误。此代码旨在防止用户两次创建相同的用户或相同的电子邮件,但仅适用于用户名。我错过了什么,还是只是一个愚蠢的错误?我正在使用两个if语句来尝试实现这一点(如注释中所述),但它无效。

提前致谢

$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 个答案:

答案 0 :(得分:0)

你只需要另一个查询:))):

$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;
}

你应该更好地使用:

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

因为如果它不相等,可以注册新用户: - )