Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert in to two tables

Tags:

mysql

Is it possible to insert in to two tables at once? I need to insert some data in to a table(contactinformation) and then based on the primary key insert in to a userstable and have the primarykey set as a field (foreign key) . Is this possible?

Thanks

like image 403
Biscuit128 Avatar asked Oct 08 '22 10:10

Biscuit128


1 Answers

You can write a procedure for this.

DELIMITER //  

CREATE PROCEDURE `proc1` (contactinformation colums... usertable columns...)  
BEGIN  
    INSERT INTO contactinformation values(contactinformation colums ...);
    INSERT INTO usertable values(LAST_INSERT_ID(), contactinformation colums ...);
END//

DELIMITER ;  

contactinformation colums... means the column definitions of contactinformation table.
usertable columns... means the column definitions of usertable table.

After the first insert you can get the insert id if contactinformation table has any auto column. Then use that key in the second insert statement.

like image 102
Shiplu Mokaddim Avatar answered Oct 12 '22 01:10

Shiplu Mokaddim