mysqlsqlinsert

Accessing last inserted row in MySQL


On my DB server, I am inserting data in a table having an auto increment field say 'id'. Now I want to use the value of this last inserted 'id' in subsequent steps. I can use this:

  select * from table_name order by id desc limit 1; 

But the problem here is, it is a server and many more insertions could be happening and there could be a case where I try to retrieve the data with the query I mentioned and get a different id, i.e. between my insert and select there could be some other insert and I won't get the value I inserted. Any way in which this could be addressed?


Solution

  • In MySQL use

       SELECT LAST_INSERT_ID();
    

    Here is the ref links

    http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html

    http://php.net/manual/en/function.mysql-insert-id.php