【问题标题】:How to know which entry is duplicated? (For example username + email)如何知道哪个条目重复? (例如用户名 + 电子邮件)
【发布时间】:2018-04-12 07:30:24
【问题描述】:

我想知道是否可以获取在 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;
        }
    }

我们如何获取重复的列信息,然后显示“电子邮件已存在”或“用户名已存在”而不是“重复条目(好的,但哪个?)

谢谢,

【问题讨论】:

标签: php mysql pdo unique-key


【解决方案1】:

您可以检查 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')");

【讨论】:

    【解决方案2】:

    感谢您的想法。没想到这个错误可以给我这个信息。 所以结果是这样的:

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

    基本上是在做这项工作。

    谢谢,

    【讨论】:

      猜你喜欢
      • 2011-11-17
      • 2016-04-13
      • 1970-01-01
      • 2020-11-28
      • 2012-03-18
      • 1970-01-01
      • 1970-01-01
      • 2017-03-31
      • 1970-01-01
      相关资源
      最近更新 更多