For example:
Table 1:
user_ID -
username -
first_name -
email -
Table 2:
message_ID -
user_ID -
message_title -
message_body -
As you can see I have user_ID as primary key in table 1, and as foreign key in the second table.
If I enter 2 rows into the first table, eg.
1, undergz, sarah, sarah@hotmail.com
2, michel21, michaele, michalzost@gmail.com
And now, michaele enters the message, and I now I add this to table 2:
1, 2, hello, hello everybody,
I added this entry in the table 2 considering first table, I added user_ID number the same as in the table 1.
I did this from $_SESSION['user_ID'] variable, when I entered the second query. So it was like
INSERT INTO table_2 VALUES (NULL, {$_SESSION['user_id']}, '$title','$message')
My question is, is this the right way to do this? We define foreign key in table so we enter data STRICTLY according to primary key, it must be the same for all values?
The question you should ask yourself is:
Can a row in the
table 2exist without a corresponding row in thetable 1?If the answer to your question is “no”, then you need the FOREIGN KEY (a.k.a. referential integrity) constraint from
table 2(“child”) totable 1(“parent”). You can think of it as having a “pointer” from one row to another, where the DBMS itself guarantees you can never have a “dangling” pointer.The “parent” set of columns in the FOREIGN KEY must always be the key, be it primary or alternate (a.k.a. UNIQUE). The “child” can be any column or combination of columns, whether they are part of a key or not. You can think of that as the parent’s key columns being propagated to the child, and depending on where the propagated columns end up, you can have the following 2 kinds of relationships:
1) “Identifying” Relationship
The parent key becomes a part of the child key (so parent “helps” identify the child):
This models either 1:N or 1:1 relationship.
2) “Non-Identifying” Relationship
The parent key does not become the part of the child’s key:
This models 1:N relationship, but requires
message_IDto be unique on its own (instead of in combination withuser_ID).