简体   繁体   English

如何在另一个链接表中插入新行的ID?

[英]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). 我有一个表,目的是用外键链接其他两个表(表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. 我用php做服务器端代码,当将一行插入table2时,我需要一种自动将一行插入表3的方法。
But i dont know how to do a php query that will get the generated id of the new row in table2? 但我不知道如何进行php查询,该查询将获取table2中新行的生成的ID?
(The id of table one i do have stored in a php variable) (表一的ID,我确实已经存储在一个PHP变量中)
Im a looking at a smart stored procedure? 我在看智能存储过程吗?

Steps to follow : 遵循的步骤

  • Insert a row into table2 . table2插入一行。
  • Find the generated key from table2 and assign it to a PHP variable. table2查找生成的密钥,并将其分配给PHP变量。
-- read this into a php variable, say, $last_key  
    SELECT LAST_INSERT_ID();
  • Use the $last_key in insert statement for table3 . table3 insert语句中使用$last_key

You can Follow below Steps: 您可以按照以下步骤操作:

1) Make ID to AUTO_INCREMENT IN Table2 1)在表2中将ID设为AUTO_INCREMENT

2) Create Store Procedure that work as below: 2)创建工作如下的存储过程:

    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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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