个性化唯一键的错误消息 mySQL

Personalize error messages for unique key mySQL

我用名称、phone 编号和评论制作了订阅公式。我在数据库中的 phone 上放置了一个唯一键,以避免多个条目具有相同的编号。 由于消息错误无法理解

Fatal error: Uncaught PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '0600000000' for key 'telephone' in C:\xampp\htdocs\sitesweb\formulaire\inscription.php:28 Stack trace: #0 C:\xampp\htdocs\sitesweb\formulaire\inscription.php(28): PDOStatement->execute() #1 {main} thrown in C:\xampp\htdocs\sitesweb\formulaire\inscription.php on line 28

我决定个性化它。 我试了一下/赶上了。 try / catch 几乎完美地工作

我是这样编码的

try{
here my sql request ...
}
 catch( PDOException $e ) {
    error_log($e -> getMessage());
    if($e->getCode()==23000){
            echo '<span class="titre_form">The phone number is already exist.</span>';
    }else{
        echo '<span class="titre_form">Thanks this person is added to the database</span>';      
    }
}

脚本运行良好(不添加已存在的 phone 个数字,添加不存在的 phone 个数字,这样就可以了)。

我的问题是我的 if 条件(当 phone 已经存在时)的第一条消息显示得很好,但是 else “谢谢这个人已添加”的消息到数据库”不显示(我只有我的背景)。

正常吗?还是我的代码出错了?

我认为它不会出现在 else 语句中,因为异常应该是“错误”,但它实际上设法将其写入数据库 ...

做这样的事情

$exist  = "no";

try{
here my sql request ...
}
 catch( PDOException $e ) {
    error_log($e -> getMessage());
    if($e->getCode()==23000){
            echo '<span class="titre_form">The phone number is already exist.</span>';
            $exist  = "yes";
    }
}

if ($exist == "no") {
        echo '<span class="titre_form">Thanks this person is added to the database</span>';      
    }