P K
P K

Reputation: 10210

Duplicate entry error for primary key which is autoincrement?

I am getting duplicate entry error for primary key which is autoincrement field defined in table.

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[23000]: 
Integrity constraint violation: 1062 Duplicate entry '0' for key 1' in

I am trying to add an entry to the table at the almost same time. That could be the possible reason but i am not sure.

Actually multiple ajax call running behind the scene and they are sometime trying to add entry in table with same primary key at the same time.

I guess this is the issue of autogeneration of same primary key by sql engine.

Mysql table type:MyISAM.

What can be done to fix this?

Table definitions: result_id is a primary key field

Table defintion

I have writren PDO wrapper for database entry, although i am using this databound object from last year and no issues found. Attaching some portion as requested in comment.

Note: ID(primary key) is not a part of INSERT statement.

$valueList = "";
$query     = 'INSERT INTO ' . $this->tableName . ' (';


foreach ($this->relationMap as $key => $value) {
    eval('$actualVal = &$this->' . $value . ';');

    if (isset($actualVal)) {
        if (array_key_exists($value, $this->modifiedRelations)) {
            $query .= $key . ', ';
            $valueList .= ":$value, ";
        }
    }
}


$query = substr($query, 0, strlen($query) - 2);

$valueList = substr($valueList, 0, strlen($valueList) - 2);
$query .= ") VALUES (";
$query .= $valueList;
$query .= ")";
//prepare and execute codes - here
$this->ID = $this->objPDO->lastInsertId();

Upvotes: 0

Views: 9606

Answers (3)

Сайф Абаза
Сайф Абаза

Reputation: 21

Make sure it is (( AUTO_INCREMENT ))

Upvotes: 0

Agee
Agee

Reputation: 1

First delete the row with id = 1 (the first record), then edit the table structure by setting the Auto_Increment attribute of the id field to 'True'(by clicking the Auto_Increment checkbox and save.)

Upvotes: 0

Abid Hussain
Abid Hussain

Reputation: 7762

Read this

Or

You have set result_id already in primary key according to your sanpshot

but i think you have not set is auto_increment

Please set primary key with auto_increment

Upvotes: 3

Related Questions