Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does a foreign key get into a table?

Tags:

php

mysql

thanks in advance for any help.

I have a question about foreign keys. I understand the concept of having the data from one table inserted into another for reference. But my question is, how does it get there?

Currently I have two tables and two forms. One form inserts data into table A, the other form inserts into B. Then I use a function to get the id from the last insert into A and insert it into B. Is this the proper way to do this or am I missing something?

like image 715
Scott Morrison Avatar asked Jun 26 '13 13:06

Scott Morrison


1 Answers

There are two possibilities :

  • You know the primary key before the insertion in table A => Then your technique isn't the right one, since you're retrieving something you already added.
  • You don't know it (Example: auto-incremented id's) => Then your technique is the right one, and I don't think there is any other better way to achieve what you are asking for.

Note that what I called the primary key is the primary key of the row in table A, and a foreign key for rows in table B.

like image 127
Jerska Avatar answered Oct 07 '22 21:10

Jerska