-2

I want to get last inserted row id in mysql any one help me Table field is

enter image description here

Ram Choubey
  • 265
  • 2
  • 12
  • 3
    possible duplicate of [MySQL - Select the last inserted row easiest way](http://stackoverflow.com/questions/2770600/mysql-select-the-last-inserted-row-easiest-way) – WorkSmarter Feb 27 '15 at 07:13

2 Answers2

2

If you want to get the id just after the insertion, use LAST_INSERT_ID():

SELECT LAST_INSERT_ID();

This will return the AUTO_INCREMENT value of the last inserted element (in your current connection).

If you want to know which is the last inserted value in a determined table, use any of the queries provided in the other answers.

Carlos Campderrós
  • 22,354
  • 11
  • 51
  • 57
1

You can use LAST_INSERT_ID(), but you should be aware that (you not only should have the AUTO_INCREMENENT), but it does operates in at connection level. This is, it will return the last_insert_id() for the current connection and not the last_insert_id() that another connection --that might be happening meanwhile-- generated.

Example (lets say the operations arrive the database in the following order):

-Connection A : user A -> insert order (id = 1000), lets say $20
-Connection B : user B -> insert order (id = 1001), lets say $50
.... multiple orders from other users are placed
-Connection B : you retrieve last_insert_id (value 1001) and you retrieve the order amount, and update the user B profile with the total revenue generated (+$50).
-Connection A : you retrieve last_insert_id (value 1000) and you retrieve the order amount, and update the user A profile with the total revenue generated (+$20).

You should be aware that last-insert_id() operates on a connection level, therefore you want to keep the connection open until you are finished. You should not use things like do a max on the database, because on a web environment you don't have control on how many users will use your app at same time, and in which order the operations will be executed and most important you want to keep your database consistent.

SQL.injection
  • 2,607
  • 5
  • 20
  • 37