1

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?

4

1 回答 1

1

您的 FK 方向错误。此刻它说:“用户表中的每个条目都必须在位置表中有一个条目。” 您尝试在用户表中插入,而不先创建位置条目。所以FK失败了。

解决方案:在位置表“user_id -> users.user_id”上设置FK,这意味着“位置表上的每个user_id都应该在用户表中有一个条目。”。唯一的问题是:“ON DELETE CASCADE”不再起作用,当您删除用户表中的条目时...... - 这可以通过数据库触发器(PSEUDOCODE)“在从用户删除之前删除用户ID的位置”来解决" 或者您只需在 PHP 中进行 2 次查询。(这是更简单的解决方案。第一个删除位置行,第二个用户行。)

于 2013-01-23T10:20:17.967 回答