title: Trying to automatically insert a foreign key value into my mysql table
body: <p>I am new with PHP and MySQL and need help...</p>
  
  <p>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?</p>
  
  <p>I have two tables...</p>
  
  <p>'mem table' 
  id, username, email.</p>
  
  <pre><code>  |    1    |    2    |    3    |
    |   paul  |   john  | francis |       
    | paul@gm.| john@gm.|francis@.|
  </code></pre>
  
  <p>'location table' 
  id, location, user_id &lt;&lt; forign key</p>
  
  <pre><code>  |    1    |    2    |    3    |
    |  leeds  |liverpool| london  |       
    |    ?    |    ?    |    ?    | 
  </code></pre>
  
  <p>how do I get the 'id' in the user table to automatically get inserted here as a foreign key?</p>
  
  <p>Im using this php code to insert the data...</p>
  
  <pre><code>$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();
  </code></pre>
  
  <p>Im getting this error when I submit the form...
  Cannot add or update a child row: a foreign key constraint fails (<code>mem</code>.<code>location</code>, CONSTRAINT <code>location_ibfk_1</code> FOREIGN KEY (<code>user_id</code>) REFERENCES <code>location</code> (<code>id</code>) ON DELETE CASCADE ON UPDATE CASCADE)</p>
  
  <p>Can anyone help?</p>