简体   繁体   中英

mySQL: insert values into 2 tables with foreign key relationship

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)

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,.......);

Unfortunately, the query doesn't work because you can't use 2 tables after the INSERT command like in my example.

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, ie the NEW data in the child table 'mobilfunkkarten' will be related to the Primary Key Number in the parent table 'mitarbeiter'.

mitarbeiter = workers mobilfunkkarten = mobile phone cards (SIM cards)

First insert the employees.

INSERT INTO mitarbeiter
            (maanrede,
             ...)
            VALUES(?,
                   ...);

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());

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