0

OK the question is NOT about how to return the ID, but more like how to skip it... I have a situation where i use last_insert_id() to get the id of the last inserted row, but i want to get a zero if no row is inserted. The problem is as follows:

  • i insert...update a few records: all IDs are returned since the rows are freshly inserted
  • then i repeat the process: this time IDs are not returned. YAY! that's exactly what i want
  • i change one column value and repeat the process: but now the ID is returned for the row i've changed the column value in. And this is making me very angry. I don't want mysql to return the ID at all if it's not inserting anything

so to sum up:

  • when inserting new records: IDs are returned
  • when inserting identical records: IDs are not returned
  • when updating a value: updated IDs of the updated rows are returned :(

Is there a workaround for this?

I know this happens because mysql probably does not perform an update on identical records, but still ... i'd sure like to know how to work around this.

4
  • If I'm not mistaken, at least for most APIs, an INSERT should return the number of rows inserted. You should be able to use this to determine if anything was inserted. Commented Nov 28, 2012 at 13:00
  • Looks like ROW_COUNT() might give you that if you're doing "raw" queries. Commented Nov 28, 2012 at 13:01
  • @ScoPi provide it as an answer - i'll click accept on it. Looks like mysql has a special behaviour for this particular query when checking ROW_COUNT() so this should work. Thanks. Commented Nov 28, 2012 at 13:05
  • stackoverflow.com/questions/778534/… Commented Nov 20, 2014 at 9:22

1 Answer 1

0

You should be able to retrieve the number of rows inserted and use that to determine if anything was inserted. If you're using "raw" queries (i.e. no API that might otherwise provide the number of rows inserted), it looks like ROW_COUNT() might give you what you want.

Sign up to request clarification or add additional context in comments.

1 Comment

To be more specific - in this situation, row count will return 1 if a row was inserted, 2 if a row was updated and 0 if it was an identical match to an existing record (so neither insert nor update).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.