payling
payling

Reputation: 2514

creating two rows at the same time with a foreign key relation

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?

Upvotes: 0

Views: 185

Answers (1)

cletus
cletus

Reputation: 625037

  • 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.

Upvotes: 2

Related Questions