如何知道哪个条目重复? (例如用户名+电子邮件)

时间:2018-04-12 07:30:24

标签: php mysql pdo unique-key

我想知道是否有可能获得在INSERT上产生重复错误的列名?

例如,使用用户名上的唯一键和电子邮件中的另一个唯一键:

    try{
        $pdo->query("INSERT INTO `table`(`username`,`email`)`VALUES('Superman','xxx@xx.com')");
    } catch (PDOException $e) {
        if($e->errorInfo[0] == '23000' && $e->errorInfo[1] == '1062'){
           throw new CustomException("Bla bla already exists");
          // How does we get the duplicated column and then display "Email already exists" or "Username already exist"
        } else {
          throw $e;
        }
    }

我们如何获得重复的列信息然后显示"电子邮件已存在"或"用户名已存在"而不是"重复录入(好但是哪一个?)

谢谢,

2 个答案:

答案 0 :(得分:0)

您可以在错误消息中为用户检查db中的值或抓取列名称。

try{
    $pdo->query("INSERT INTO `table`(`username`,`email`) VALUES ('Superman','xxx@xx.com')");
} catch (PDOException $e) {
    if (preg_match("/Duplicate entry .+ for key '(.+)'/", $e->getMessage(), $matches)) {
        throw new CustomException($matches[1]." already exist");
    } else {
        throw $e;
    }
}

也许您更喜欢将 exec 命令用于“非结果查询字符串”。

$affectedRow = $pdo->exec("INSERT INTO `table`(`username`,`email`) VALUES ('Superman','xxx@xx.com')");

答案 1 :(得分:0)

感谢您的想法。不认为错误可以给我这个信息。 因此它将导致:

    try {
        $query = $this->dbh->prepare('INSERT INTO users (username,email) VALUES ("test", "test")');
        $result = $query->execute();
    } catch (PDOException $e) {
        if( $e->errorInfo[0] == '23000' && $e->errorInfo[1] == '1062' ){
            if( strpos($e->getMessage(), 'username') == true ) $result = 'duplicate_username';
            elseif( strpos($e->getMessage(), 'email') == true ) $result = 'duplicate_email';
        } else {
            throw $e;
            $return = false;
        }
    }

基本上是在做这项工作。

谢谢,