I am new with PHP and MySQL and need help...
Im cant seem to get my head around how to automatically insert a foreign key into a table in my database. The primary key gets added as 'id' in my 'mem' table but I want this same id to be added to a foreign key in my 'location' table. Can anyone please help?
I have two tables...
'mem table' id, username, email.
| 1 | 2 | 3 |
| paul | john | francis |
| paul@gm.| john@gm.|francis@.|
'location table' id, location, user_id << forign key
| 1 | 2 | 3 |
| leeds |liverpool| london |
| ? | ? | ? |
how do I get the 'id' in the user table to automatically get inserted here as a foreign key?
Im using this php code to insert the data...
$sql = mysql_query("INSERT INTO mem (username, country, state, city, accounttype, email, password, signupdate)
VALUES('$username','$country','$state','$city','$accounttype','$email','$hashedPass', now())") or die(mysql_error());
$id = mysql_insert_id();
$sql = mysql_query("INSERT INTO location (location)
VALUES('$location')") or die(mysql_error());
$user_id = mysql_insert_id();
Im getting this error when I submit the form...
Cannot add or update a child row: a foreign key constraint fails (mem
.location
, CONSTRAINT location_ibfk_1
FOREIGN KEY (user_id
) REFERENCES location
(id
) ON DELETE CASCADE ON UPDATE CASCADE)
Can anyone help?