Click here to Skip to main content
15,888,014 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
Suppose we have MySQL server that many clients can access it, and suppose yourself a client and you want to INSERT a record in that shared Data Base.
The question is how to hold the auto-incremented table id of the inserted record?

What I have tried:

I have tried to use :
LAST_INSERT_ID()
function that returns last incremented id in the database but this function will not be useful because many client can do multiple insert and update statements. So the returned id which is the most recent one can be altered by another update/insert statement from different client.
Also, i have tried to use a session variable to store the value returned by that function
SET @X = LAST_INSERT_ID()
But is there another professional way to do this?
Posted
Updated 16-Feb-18 10:47am
Comments
PIEBALDconsult 16-Feb-18 17:59pm    
Better to know the ID _before_ you insert it.

1 solution

LAST_INSERT_ID() is the solution. Have a look at that SO post:
SO: Get the new record primary key ID from mysql insert query?[^]
The ID that was generated is maintained in the server on a per-connection basis. This means that the value returned by the function to a given client is the first AUTO_INCREMENT value generated for most recent statement affecting an AUTO_INCREMENT column by that client.

You can also check MySQL documentation directly:
Function LAST_INSERT_ID()[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900