Help with MySQL last_Insert_id() on multiple insert


Hi

I have a multiquery statement like the example below where the first query inserts a record.

The second query then adds a relationship to another table using the last_insert_id() function.

The third query I wish to also put the last_insert_id() value from the first query but it's obviously taking the id of the second query.

is there any way to save or reuse the last_insert_id() from the first query? (for use in the 3rd query)

INSERT INTO tbl_contacts (name)
VALUES ("Shaun Perry");
INSERT INTO lnk_contacts (contactId)
VALUES (LAST_INSERT_ID());
INSERT INTO lnk_projects (projectId, contactId)
VALUES (1, LAST_INSERT_ID());

Kind regards

Shaun
wiredmonkeyAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

theGhost_k8Database ConsultantCommented:
You may store it in a variable and use it!
0
john-formbyCommented:
I guess you are using something like PHP to populate?

You can do like theGhost_k8 said and store as a variable:

$lastinsert = mysql_insert_id;

Then use $lastinsert in your queries.

Hope this helps,

John
0
wiredmonkeyAuthor Commented:
Hi

I managed to work this out myself using MySQL temporary variables:

INSERT INTO tbl_contacts (name)
VALUES ("Shaun Perry");

SELECT @myname:=LAST_INSERT_ID();

INSERT INTO lnk_contacts (contactId)
VALUES (@myname);

INSERT INTO lnk_projects (projectId, contactId)
VALUES (1, @myname);

Thanks

Shaun
0
ee_autoCommented:
Question PAQ'd, 500 points refunded, and stored in the solution database.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
MySQL Server

From novice to tech pro — start learning today.