views:

97

answers:

1

using php and mysql

I have two tables, a users table and a profiles table.

When a new account is created on my site the user and profile rows are created at the same time.

I want a foreign key to reference from the users table to the profiles table so that the users profile information will be stored in a seperate table.

My questions is, how do I ensure that the foreign key links to the correct profiles table.

The current way I would go about doing this is, after the new user and profiles row was created I would query the profiles in descending order to get the last row created and grab the profile id and insert it into the users table profile id foreign key reference. I'm sure that there must be a better way to do this though.. isn't there?

+2  A: 
  • Create user with mysql_query();
  • Assuming the primary key of the users table is an auto-increment field, call mysql_insert_id();
  • Use that as the foreign key when you insert the profile.
cletus
+1 Too fast. ;)
Paolo Bergantino
Aye, pretty straight forward to be honest.
Kezzer
IMHO the only good way for mysql. The others are kind of hacks.
Jet
wasn't aware of the mysql_insert_id() function.. but not that I am.. easy as pie
payling