dynamic
dynamic

Reputation: 48141

get the primary key after a DUPLICATE KEY error?

If I run an insert query but it fails because of duplicated key error is there any way to get its primary key without doing another select?

Basically:

INSERT INTO tbl (field) VALUES ('myvalue')

This fails because there is already a record with ID:1 and field:myvalue.

Now I Want to know that ID:1 without doing another query:

SELECT id FROM tbl WHERE field = 'myvalue'

is it possibile?

Upvotes: 3

Views: 776

Answers (2)

Christopher Masser
Christopher Masser

Reputation: 829

Here is a link that provides four different ways to deal with this: http://mikefenwick.com/blog/insert-into-database-or-return-id-of-duplicate-row-in-mysql/

Upvotes: 2

Vipin Jain
Vipin Jain

Reputation: 1402

There is a provision with each library to get the id of the row which is inserted.

Like: for simple mysql_query() use mysql_insert_id() after that to retrive the id of the last inserted row

Check this link

EDIT:

Please Check that if you have defined the unique index for field column.

If yes then you cannot insert duplicate in the column field

Upvotes: 0

Related Questions