使用PDO的Mysql错误消息

时间:2017-11-26 23:10:18

标签: mysql pdo error-messaging

我希望我的数据库不要插入重复的电子邮件,我使用了唯一的密钥,它完美无缺。但是,没有向用户显示任何消息,似乎他正确注册,但当他尝试登录时,他发现它是不可能的。

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

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

1 个答案:

答案 0 :(得分: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.';
    }