简体   繁体   中英

Multiple insert with last_insert_id in a transaction

I've got a series of records to insert to a database, but the structure of database requires a special approach:

BEGIN;
table contact -> firstname,lastname
table company -> name
table contact_company_vs -> contact_id,company_id (THESE TWO ARE LAST_INSERT_IDs FROM first two inserts)
COMMIT;

How to do that? Should I limit myself to php capabilities of storing variables by doing a few inserts one after another?

actually you can do this either with php or with sql

PHP

  1. use mysqli/pdo and innodb tables
  2. set autocommit to off
  3. insert 1 -> save $id (you can get it via mysqli_insert_id and it will work properly inside transaction)
  4. insert 2 -> save $id2
  5. insert 3 -> you have $id and $id2
  6. commit all changes
  7. if any errors during logic - rollback them

SQL

I prefer to use stored procedures:

declare id1 bigint default 0;
declare id2 bigint default 0;
insert1 ... ;
SELECT LAST_INSERT_ID() into id1;
insert2 ... ;
SELECT LAST_INSERT_ID() into id2;
insert into contact_company_vs values(id1, id2);
select id1, id2;

such stored proc will even return both generated ids back into your logic

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM