简体   繁体   中英

How to insert a id of a new row into another linking table?

I've a table with the purpose of linking two other tables with foreign keys (table 3).

table1 = id, name
table2 = id, sport
table3 = fk_table1_id, dk_table2_id

I do server side code with php and i need a way to automatic insert a row into table 3 when a row is inserted into table2.
But i dont know how to do a php query that will get the generated id of the new row in table2?
(The id of table one i do have stored in a php variable)
Im a looking at a smart stored procedure?

Steps to follow :

  • Insert a row into table2 .
  • Find the generated key from table2 and assign it to a PHP variable.
-- read this into a php variable, say, $last_key  
    SELECT LAST_INSERT_ID();
  • Use the $last_key in insert statement for table3 .

You can Follow below Steps:

1) Make ID to AUTO_INCREMENT IN Table2

2) Create Store Procedure that work as below:

    A) INSERT Value to your Table2 :

    B) Increase ID value :  SELECT LAST_INSERT_ID() INTO VARIABLE; 

    C) Insert Value to your Table3   : use VARIABLE to get ID of Table2

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