2

I have a query like so:

INSERT INTO table1 (field1,field2) VALUES ('$value1','$value2') ON DUPLICATE KEY UPDATE field1 = '$value1'

I then want to get the last insert id if it does the insert, how can I do this? If the query ends up doing an update I dont want the last insert id. Is there a way to determine if it did an update or a insert?

John
  • 9,840
  • 26
  • 91
  • 137
  • 1
    possible duplicate of [MySQL ON DUPLICATE KEY - last insert id?](http://stackoverflow.com/questions/778534/mysql-on-duplicate-key-last-insert-id) – Phrogz Dec 31 '10 at 03:52
  • 1
    possible duplicate of ["INSERT IGNORE" vs "INSERT ... ON DUPLICATE KEY UPDATE"](http://stackoverflow.com/questions/548541/insert-ignore-vs-insert-on-duplicate-key-update) – jensgram Nov 09 '11 at 06:55

2 Answers2

2

I guess I should of searched the site before posting. Basically adding this worked:

id=LAST_INSERT_ID(id)

On the on duplicate update. I found that answer here:

Duplicate Key Last Insert ID

Community
  • 1
  • 1
John
  • 9,840
  • 26
  • 91
  • 137
1

According to this MySQL Manual Page:

If a table contains an AUTO_INCREMENT column and INSERT ... ON DUPLICATE KEY UPDATE inserts or updates a row, the LAST_INSERT_ID() function returns the AUTO_INCREMENT value.

Phrogz
  • 296,393
  • 112
  • 651
  • 745