views:

48

answers:

1

I am inserting a row into a table and would like to get the value of the automatically incremented primary index.

The primary index is the only unique value in the table so I don't want to do anything like "SELECT [primary index] FROM [table] WHERE [the columns = the data I just inserted]" to prevent ambiguity. I also don't want to SELECT the last row since a row might have been inserted in between my INSERT and SELECT statements.

I could INSERT an empty row, SELECT the primary index and UPDATE the row with the data but that seems like quite an ugly hack. This leads me to believe that their MUST be a way to get the primary index of the row you just inserted through the mysqli API since I would think this would be very ubiquitous thing to do.

Can someone enlighten me?

+4  A: 

mysql_insert_id() is your answer.

You tagged your question with "mysqli" as well, in which case you'd use mysqli->insert_id().

zombat
In the time it took me to google it and write out an answer you already had on there. I suppose I would have won if I knew php in the first place.
Iuvat