简体   繁体   English

将新创建的id值作为外键插入到另一个表的列中

[英]Insert newly created id value into the column of another table as Foreign key

Hello everyone PHP and mysql noob here 大家好,PHP和mysql noob在这里

I'm creating a form to create a new user and at the same time add a contact 我正在创建一个表单以创建一个新用户,并同时添加一个联系人
but user and contact are in two different table 用户联系人位于两个不同的表中

and i need the newly user_ID to reference the user_ID (FK) in the tbl_contact 我需要新的user_ID来引用tbl_contact中user_ID (FK)

how would i do it? 我该怎么办?

first of all insert the user 首先插入用户

mysql_query("INSERT INTO tbl_user (...) VALUES (...)");

then retrieve the last inserted id 然后检索最后插入的ID

$LIid=mysql_insert_id();

then insert the contact with this id 然后插入具有此ID的联系人

mysql_query("INSERT INTO tbl_contact (user_ID,...) VALUES ($LIid,...)");

Refrence 提神

If you want to use mysqli 如果要使用mysqli

$mysqli->query("INSERT INTO tbl_user (...) VALUES (...)");
$LIid=$mysqli->insert_id;
$mysqli->query("INSERT INTO tbl_contact (user_ID,...) VALUES ($LIid,...)");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM