Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

INSERT and then SELECT the inserted row

My table Structure,Table Name- user_tb

User_Id  Name      Mob_No   City
=================================
100      Sumith    34542    dfsc
101      Yadhu     35485    dfgd
102      Aby       34234    jhhg

Here column User_Id is auto_increment and am inserting values to this table using this query,

insert into user_tb(Name,Mob_No,City) values('Yadhu',34542,'dfsc');

I need to get User_Id of the Person at the time of insertion ie, when am inserting using this query,

insert into user_tb(Name,Mob_No,City) values('Yadhu',34542,'dfsc');

i need to get User_id-101 Is this possible....

Anyone please help me to complete this.

like image 981
user3841250 Avatar asked May 25 '26 17:05

user3841250


1 Answers

Obtaining the value of column that uses AUTO_INCREMENT after an INSERT statement can be achieved in a number of different ways. To obtain the value immediately after an INSERT, use a SELECT query with the LAST_INSERT_ID() function.

For example, using Connector/ODBC you would execute two separate statements, the INSERT statement and the SELECT query to obtain the auto-increment value.

insert into user_tb(Name,Mob_No,City) values('Yadhu',34542,'dfsc');
SELECT LAST_INSERT_ID();

If you do not require the value within your application, but do require the value as part of another INSERT, the entire process can be handled by executing the following statements:

insert into user_tb(Name,Mob_No,City) values ('Yadhu',34542,'dfsc');
insert into tbl2 (id,text) VALUES (LAST_INSERT_ID(),'text');
like image 144
Nadeem_MK Avatar answered May 28 '26 07:05

Nadeem_MK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!