0

我希望我的数据库不要插入重复的电子邮件,我使用了唯一键并且它工作得很好。但是,没有向用户显示任何消息,并且看起来他注册正确,但是当他尝试登录时,他发现这是不可能的。

我制作了这段代码,但它在两种情况下都返回成功。

$sql4 = "INSERT INTO users (username, email, password, id_group, id_company) 
VALUES (:username, :email, :password, :id_group, :id_company)";
   $stmt4 = $PDO->prepare($sql4);
   $stmt4->bindParam(':username', $username);
   $stmt4->bindParam(':email', $email);
   $stmt4->bindParam(':password',md5($password));
   $stmt4->bindParam(':id_group', $id_group);
   $stmt4->bindParam(':id_company', $id_company);
   $stmt4->execute();

$erro = mysql_errno();
if ($erro == 0) {
    echo '<p align="center">Success!</p>';
} elseif ($erro == 1062) { 
    echo '<p align="center"> Email already registered. Try using another.
</p>';
} 
4

1 回答 1

0

我尝试了另一种方法,它奏效了:

$sql4 = $PDO->prepare("SELECT COUNT(*) as us FROM users WHERE email = 
:email");
    $sql4->bindValue(":email",$email);
    $sql4->execute();
    $row = $sql4->fetch();

    if($row['us'] == '0'){

$sql4 = "INSERT INTO users (username, email, password, id_group, id_company) 
VALUES (:username, :email, :password, :id_group, :id_company)";
$stmt4 = $PDO->prepare($sql4);
$stmt4->bindParam(':username', $username);
$stmt4->bindParam(':email', $email);
$stmt4->bindParam(':password',md5($password));
$stmt4->bindParam(':id_group', $id_group);
$stmt4->bindParam(':id_company', $id_company);
$stmt4->execute();

return '1';
    //se o email for repetido exibe mensagem de erro.    
    }else{
        echo 'Email already registered. Try another.';
    }
于 2017-11-27T01:13:49.523 回答