如何在DB中使用UNIQUE字段时捕获查询错误消息?

时间:2015-11-02 11:03:43

标签: php mysql

我正在将表单值插入到DB中。我想知道如果在将此字段设置为唯一时db中已存在值,则如何打印错误消息。这是db表设计

id(PRIMARY KEY auto_increment) name(char) email(UNIQUE) password(char) date

这里有插入代码:

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();
  }

插入部分工作得很好......但是如果电子邮件已经存在于db

中,我将如何打印错误消息

1 个答案:

答案 0 :(得分:0)

我认为你的意思是如何捕获错误,你可以使用$e->getMessage()

来实现
 try {
  //code
 } catch(PDOException $e) {
   $errorinsert = $e->getMessage();
   include_once'error_page.html.php';
   exit();
 }

来源:http://php.net/manual/en/language.exceptions.php