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 ^_^
Inserting into a table with a foreign key
Moderator: General Moderators
I'm stupid
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 ^_^
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 ^_^