Home > Software engineering >  Personalize error messages for unique key mySQL
Personalize error messages for unique key mySQL

Time:02-21

I made a formular for a subscription with a name, a phone number and a comment. I put a unique key on the phone in my database to avoid several entries with the same number. As the message error is incomprehensible

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

I decided to personalized it. I put a try / catch. The try / catch works almost perfectly

i coded it like that

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

The script work good (a phone number existing is not added a second time and a phone not existing is added so it is ok).

My problem is the first message of my if condition (when a phone already exist) is well displayed, but the message of the else "Thanks this person is added to the database" is not displayed (I have only my background).

Is it normal ? Or did I make an error in my code ?

CodePudding user response:

I think it's not going on the else statement since exception are supposed to be "error" but it actually manage to write it on database ...

do something like this

$exist  = "no";

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

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

  • Related