PDO - Uncaught PDOException: SQLSTATE[23000]: Integrity constraint violation

时间:2017-12-18 06:11:05

标签: php mysql

How to Fix this issue?

Uncaught PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry

I use UNIQUE KEY on My Table

CREATE TABLE `blog` (
  `id` int NOT NULL AUTO_INCREMENT,
  `title` varchar(100) NOT NULL,
  `str` varchar(100) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `title` (`title`),
  UNIQUE KEY `str` (`str`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

if I enter the same data for times I got this error

if I create datable without UNIQUE KEY it's working well

My PDO Insert code

$sql = "INSERT INTO blog(title,str) VALUES(:title,:str)";
 $stmt = $DBcon->prepare($sql);
 $stmt->bindparam(':title', $title,PDO::PARAM_STR);
 $stmt->bindparam(':str', $str,PDO::PARAM_STR);
 $stmt->execute();

if I remove the $stmt->execute(); the UNIQUE KEY concept working well

I tried on MYSQLI it works without any issue But in PDO I got this error

1 个答案:

答案 0 :(得分:0)

you have define unique key for title and str so it not allow insert duplicate value in this field

 UNIQUE KEY `title` (`title`),
 UNIQUE KEY `str` (`str`)

The UNIQUE constraint ensures that all values in a column are different.

Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for uniqueness for a column or set of columns.

A PRIMARY KEY constraint automatically has a UNIQUE constraint.