Jump to content

FK to automatically be set


mpsn

Recommended Posts

Hi, I was wondering if it is possible to have the foreign keys (FK) to automatically assign its value to the corresponding PK (primary key) it references?

Let's say I have four tables (with their PK,FK and other fields)

TABLE document:    TABLE pathway:      TABLE leaf       TABLE value:
PK: docID               PK:pathID               PK:leafID         PK:valueID
filePath                   pathway                 FK:pathID       FK:leafID
fileName                                                  FK:docID         value
                                                                target
                                                                source

So when I upload a document, it is added to TABLE document, where PK docID set, and at same time I would add the filepath to TABLE pathway, and now I want TABLE leaf's FK to AUTOMATICALLY add the pathID, docID and ALSO at same time TABLE value's FK of leafID will also be added for that ONE entry that was initally added to TABLE document, pathway.

 

Please I hope someone understand what I want to do, I know FK is for ensuring integrity of data. Please any help is appreciated. Please use my example to help me, thanks.

 

PS: I know the formatting is off which I noticed when I went to preview the post, sorry.

Link to comment
Share on other sites

The short answer is no. The database doesn't do anything "automatically" - you need to tell it what to do. But, creating a process to do all that is a fairly simple task. One function that you may not be aware of that makes this easy is mysql_insert_id() which will return the unique ID of the last inserted record. So, right after you INSERT the record into the 'document' table you can set $docID as follows

$docID =mysql_insert_id(); 

 

you can then use that variable in the subsequent INSERTS that need that foreign key.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.