mySQL:将值插入具有外键关系的2个表中 [英] mySQL: insert values into 2 tables with foreign key relationship
问题描述
我创建了2个具有以下结构的表:
I have created 2 tables with the following structure:
mitarbeiter
==================
maID (PK, AUTO_INCREMENT, NOT NULL)
maAnrede
maName
maVname
maDurchwahl
maEmail
maMobilfunkNr
maKartenanzahl
maFirma
mobilfunkkarten
==============================
mfkID (PK, AUTO_INCREMENT, NOT NULL)
mfkTarif
mfkStatus
mfkKartennr
mfkPin
mfkSuperpin
maID(FK)
现在,我希望网络用户在表单字段中输入值.单击保存"按钮后,数据将保存到相应的2个表中. 我的mySQL查询看起来像这样:
Now I would like the web user to type in values into form fields. After clicking the "Save"-Button, the data will be saved into the corresponding 2 tables. My mySQL-Query looks like this:
INSERT INTO mitarbeiter,mobilfunkkarten
(maAnrede, maVname, maName, maMobilfunkNr, mfkTarif, maKartenanzahl, mfkStatus, mfkkartennr, mfkPin, mfkSuperpin, maEmail, maFirma)
VALUES($anrede, $Vorname, $Nachname,.......);
不幸的是,该查询无法正常工作,因为您不能像我的示例一样在INSERT命令之后使用2个表.
Unfortunately, the query doesn't work because you can't use 2 tables after the INSERT command like in my example.
任何解决方案如何解决呢?我只是想不出办法确保将用户在表单字段中键入的任何内容保存为这2个表中的1个数据集,即子表"mobilfunkkarten"中的NEW数据将与父表"mitarbeiter"中的主键号.
Any solutions on how to solve this? I just can't think of any way on how to make sure that anything the user types into the form fields will be saved as 1 dataset into these 2 tables, i.e. the NEW data in the child table 'mobilfunkkarten' will be related to the Primary Key Number in the parent table 'mitarbeiter'.
mitarbeiter =工人 mobilfunkkarten =手机卡(SIM卡)
mitarbeiter = workers mobilfunkkarten = mobile phone cards (SIM cards)
推荐答案
首先插入员工.
INSERT INTO mitarbeiter
(maanrede,
...)
VALUES(?,
...);
然后插入SIM卡.使用 last_insert_id()
获取为员工记录创建的ID.
Then insert the SIM card. Use last_insert_id()
to get the ID created for the employee record.
INSERT INTO mobilfunkkarten
(mfktarif,
...,
maID)
VALUES (?,
...,
last_insert_id());
这篇关于mySQL:将值插入具有外键关系的2个表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!