如何使用外键一次在2个mysql表中插入数据

时间:2014-03-27 10:07:16

标签: php mysql

我有2个mysql表tbl_accounttbl_user。我想使用一个表单将数据添加到两个表中。我想插入以下内容,

tbl_account = account_idaccount_namesecret_key

tbl_user = user_idaccount_iduser_name

我正在做的是,在tbl_account中插入数据,然后从该表中提取account_id,然后在account_id中插入相同的tbl_user。我通过表单中传递的account_id获取secret_key。这是正确的方法还是有任何简单的方法来做到这一点。请建议

1 个答案:

答案 0 :(得分:0)

在我看来,将它放在2个表中更容易,而不是将其插入第一个表中,将其读出,然后再插入。

所以我会做这样的事情:

$con = mysqli_connect("host","username","password","database");
mysqli_query($con,"INSERT INTO `tbl_account` (account_id, account_name) VALUES ('$account_id', '$account_name';");
mysqli_query($con,"INSERT INTO `tbl_user` (user_id , account_id, user_name) VALUES ('user_id', '$account_id', '$account_name';");