mpsn Posted October 30, 2011 Share Posted October 30, 2011 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. Quote Link to comment https://forums.phpfreaks.com/topic/250127-fk-to-automatically-be-set/ Share on other sites More sharing options...
Psycho Posted October 30, 2011 Share Posted October 30, 2011 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. Quote Link to comment https://forums.phpfreaks.com/topic/250127-fk-to-automatically-be-set/#findComment-1283536 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.