Forum Moderators: coopster & phranque

Message Too Old, No Replies

mySQL and Foriegn keys

looking for resources

         

ukgimp

11:12 am on Jul 24, 2002 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hello

Im am starting out with php and mySQL and have got the basic inserts,display,deletes sorted (most of the time).

What I am looking to do next is insert related records in different tables. I need to find out how to deal with PK and FK's.

For example say I have two tables:

"T1"
PK
Value 1
Value 2

"T2"
PK
FK
Value 3
Value 4

Is this the best method. I need to read up on this. Resources, resources, I need them :-)

sparrow

1:42 pm on Jul 24, 2002 (gmt 0)

10+ Year Member



I think what you are looking for is a "join" statement, where based on your variables you join the to tables to develop a 3rd.

We use this in a couple of our websites, it can get a bit trick but it works very nicely.

The best resource is still mysql.com and php.net

After reading your post again, I'm not sure I understand what you are asking?

ukgimp

2:02 pm on Jul 24, 2002 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Thanks for the reply Sparrow

I suppose what I am trying to find out / learn is the best way of inserting joined data that is in different table.

So for the example during an insert into :

"USER"
PKUser
Field(s)

"EVENTS"
PKEvents
Field(s)

Where the relationship between USER and EVENTS is 1-Many. mySQL does not allow for FK, so do I need to create another Field in EVENTS that is the PK for the USER. I inderstand how to get the data out EG

SELECT * FROM USER
WHERE USER.PKUSER = EVENTS.PKEvents

But how do you go about INSERTING, is it the same thing. I suppose I am looking for the best way, so I use that method from the start. The most efficient and to be honest I dont know what methods would work.

Cheers

jatar_k

4:01 pm on Jul 24, 2002 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



OK, I have rewritten this post three times already.

your two posts have a variation on the keys so for clarity I am talking about this model

"USER"
PKUser
Field(s)

"EVENTS"
PKEvents
FKUser
Field(s)

It is understood that mysql does not support foreign keys. You still need a field for the PKUser so you can connect the tables. When you are inserting I would assume that the user will exist in advance and can be created without having an event attributed to it. An event must always be attributed to a user when it is created. So when creating a user you would be doing just that and inserting only user data. When you insert an event it must be attributed to user so you can select the id for that user and then include it in your insert for the event table.

I could have misunderstood your situation but I don't see the confusion. A user row is independant because no other tables are referenced but an event must always have a previously created user to attach to. The inserts should both be individual events.