check for duplicate entry vs use PDO errorInfo result

前端 未结 4 1611
被撕碎了的回忆
被撕碎了的回忆 2020-12-24 07:12

I have a MySQL table which has a field for email addresses which is defined as unique. For this example, let\'s say that all my form does is allow a user to insert their em

4条回答
  •  暖寄归人
    2020-12-24 07:32

    A simpler way that works for me is to check the error code against an array of duplicate status codes.That way you dont have to worry what PDO returns.

    $MYSQL_DUPLICATE_CODES=array(1062,23000);
    try {
       $prep->execute($values);
       // do other things if successfully inserted
    } catch (PDOException $e) {
       if (in_array($e->getCode(),$MYSQL_DUPLICATE_CODES)) {
          // duplicate entry, do something else
       } else {
          // an error other than duplicate entry occurred
       }
    }
    

    Thanks! :-)

提交回复
热议问题