Inserting into a table with a foreign key

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
User avatar
katchoo
Forum Newbie
Posts: 10
Joined: Mon Aug 11, 2003 6:49 pm

Inserting into a table with a foreign key

Post by katchoo »

Okay this may be ridiculously easy, but I have searched here and about five other sites with no answer.

Error:Cannot add or update a child row: a foreign key constraint fails

Code:
$query =mysql_query("insert into testaddress(Address1,Address2,City,State,Zipcode,Phone1)VALUES('$address1','$address2','$city','$state','$zipcode','$phone1')") or die(mysql_error());
$insertedID = mysql_insert_id();
$query2 =mysql_query("insert into test_php (AddressID,Firstname,Lastname,email,optin,Contact,NumGames)VALUES('$insertID','$fname','$lname','$email','$optin','$contact','$numgames')") or die(mysql_error());

What I am trying to accomplish:
I have an address table that is grabbing the address info from the form and inserting that data into an address table with the auto incremented id AddressID. That part is working.

I use mysql_insert_id(); to get the id of that address record.

I then try to assign it to the foreign key of AddressID in the CustomerInfo(test_php) table. Where the error comes up.

I may be totally wrong in how I am doing this, but I can't find any example on how to update a table with a foreign key.

Any help would be appreciated even if it's just a link to a site. It is my understanding that an Insert Select will not work because I have to insert data from the form also not just from the other table. Obviously there is a way to do this because everyone uses foreign keys, but I can't find a single post on this error.

Thank you so much for your time.
Trina ^_^
User avatar
katchoo
Forum Newbie
Posts: 10
Joined: Mon Aug 11, 2003 6:49 pm

I'm stupid

Post by katchoo »

So basically I have it right, but my variable on the second insert was insertid instead of insertedid.

So it now works. But if you have any better ways of achieving this result please feel free to post so that I can learn better coding practices.

Thanks,
trina ^_^
Post Reply