diya diya - 7 months ago 24
SQL Question

How to use last_insert_id() in mysql

My SQL statements like this:

insert into foo (val1) values ('v1'); # ID in first table
foo_id = select last_insert_id();

insert into bar (val2) values ('v2'); # ID in second table
bar_id = select last_insert_id();

insert into foobar (foo_id, bar_id, val3) values (foo_id, bar_id,'text'); # third table


The above is not working, it doesn't recognize the foo_id = statement.

Answer
insert into foo (val1) values ('v1');  -- ID in first table
SET @foo_id = last_insert_id();

insert into bar (val2) values ('v2');  -- ID in second table
SET @bar_id = last_insert_id();

insert into foobar (foo_id, bar_id, val3) values (@foo_id, @bar_id,'text'); -- third table
Comments