How does a foreign key get into the table?

in advance for help.

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

I currently have two tables and two forms. One form inserts data into table A, another form inserts into B. Then I use the function to get the identifier from the last insert in and paste it into B. Is this the right way for this or am I missing something?

+6
source share
3 answers

There are two possibilities:

  • You know the primary key before inserting into the table A => Then your technique is incorrect, because you are extracting what you have already added.
  • You don’t know this (example: auto-incremented id's) => Then your technique is correct, and I don’t think there is another 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 the foreign key for the rows in table B.

+6
source

The short answer is, I do not believe that you have missed anything. There are many ways to achieve what you need, but your explanations are probably the most commonly used and understood.

Another way is to use a trigger in table A to populate table B after insertion (this only works if you do not need any additional user input, for example, entering a form to insert into table B).

+1
source

Since you cannot insert two identifiers at the same time, yes, that was the correct way.

  • First insert the record into the main table that we know it.
  • Secondly, you, the last insert identifier, using the mysqli_insert_id() function
  • Now paste the data into a foreign table using this primary key.
-1
source

Source: https://habr.com/ru/post/948141/


All Articles