如何在Table1中插入PK(主键)到表2中的FK(外键)然后显示结果

时间:2011-07-22 09:49:02

标签: php mysql insert foreign-keys primary-key

我遇到mysql和PHP的问题。 首先 我有2张桌子:

table_customer

  • id_cust - > auto_increment,not null和PK
  • cust_name
  • 地址

table_list

  • id_list - > auto_increment,not null和PK
  • id - >来自table_customer的FK
  • LIST_NAME
  • 细节

我想问一下如何将数据插入到那些表中,必须填写表客户,但table_list是可选的, 然后如何用PHP显示它,因为我已经尝试过它失败了。我希望有人可以帮助我。

我的PHP代码是这样的:

<?php

$insert = mysql_query("INSERT INTO id_cust (cust_name, address, sex)
VALUES ('$name', '$address', 'sex')");

?>

我不明白我应该在SELECT命令中插入FK表。

1 个答案:

答案 0 :(得分:0)

您应该按顺序执行查询:

//to begin transaction (lock the table)
BEGIN

//insert your customer
INSERT INTO table_customer (cust_name, address, sex) VALUES ( '$name' , '$address', '$sex')

//select last auto generated ID from customer table
SELECT id FROM table_customer ORDER BY id DESC LIMIT 1

//fetch the id selected in last query to $cID and use it in this query
INSERT INTO table_list (id, list_name, detail) VALUES ( $cID, '$listName', '$detail' )

//commit changes and end transaction
COMMIT

记住这只是一个例子,我没有写任何PHP代码(我指责你可以自己做)。为了使它工作,你将不得不改变点点滴滴。但关键是LOCK和UNLOCK表(使用事务),因此在您真正获得最新ID之前,不能向客户添加其他行...