MySQL Insert Error Duplicate entry for key ‘PRIMARY’

I use the following PHP code to debug my PHP code and found the error message: Insert Error Duplicate entry for key ‘PRIMARY’. It turns out that I forget to add the AUTO_INCREMENT to the Primary Key when creating that table.

if (!$stmt->execute()) {
    echo "PDOStatement::errorInfo(): ";
    $arr = $stmt->errorInfo();

And the error message is like:

PDOStatement::errorInfo(): Array ( [0] => XXX [1] => XXX [2] => Duplicate entry ’0′ for key ‘PRIMARY’ )

So lesson learned: when creating a table, we usually use a unique id as the primary key and expect it automatically increment itself without specifying this attribute when doing insertion. Do not forget add AUTO_INCREMENT to that primary key if you expect as what I did here.



Written on November 1, 2014