How can i catch a query error message when using UNIQUE for a field in DB?

Hi,
I am working on insert form values into DB. I want to know how to print an error message if a value already exists in db when setted this field to unique. Here is the db table design.

[php]id(PRIMARY KEY auto_increment) name(char) email(UNIQUE) password(char) date.[/php]

Here is there insert code:
[php]
try {
$sql = “INSERT INTO user_registration SET
nom=:nom,
prenom=:prenom,
email=:email,
password=:password,
sexe=:sexe,
regis_date=CURDATE()”;

$s = $pdo->prepare($sql);

$s->bindValue(’:nom’, $_POST[‘nom’]);

$s->bindValue(’:prenom’, $_POST[‘prenom’]);

$s->bindValue(’:email’, $_POST[‘email’]);

$s->bindValue(’:password’, password_hash($_POST[‘pwd1’], PASSWORD_DEFAULT));

$s->bindvalue(’:sexe’, $_POST[‘sexe’]);

$s->execute();

if ($s) {
echo “insert good”;
exit();
}
} catch (PDOException $e)
{
$errorinsert=‘Error inserting values’;
include_once’error_page.html.php’;
exit();
}
[/php]
The insert part works great…But how i can print the error message if the email already exists in db

If you have a unique index on the column the error message will be in $e.

to see it just echo $e in your catch block

Check the error code. You are looking for a 23000 error code.

Here is a method:
[php] public function insertUser( $name = null, $password = null, $email = null ) {
$requiredFields = array (
‘:user’ => $name,
‘:pass’ => $password,
‘:email’ => $email
);

if( $this -> validateData( $requiredFields ) ) {
  $sql = <<<SQL
 INSERT into user
   ( fname, password, email )
 VALUES
   ( :user, :pass, :email );

SQL;

  try {
    $stmt = $this -> pdo -> prepare( $sql );
    $stmt -> execute( $requiredFields );
    
    if( $stmt -> rowCount() )
      return 'User added';
  } catch( PDOException $ex ) {
    switch( $ex -> getCode() ) {
      case 23000:
        return "User already exists";
        break;
      default :
         return "There was an error creating the user";
        // for development you want the actual error message however
    }
  }
}

}[/php]

Sponsor our Newsletter | Privacy Policy | Terms of Service