简体   繁体   English

用PHP插入Mysql-外键插入问题

[英]Insert Mysql with PHP - problem with foreign key insert

[project_select]
UserID (fk) | project_id (fk) | project_category_id (fk)

[project_category]
project_category_id | category

[projects]
project_id | projectname

[project_user]
UserID | Name

How can I insert Data with php in the tables project_category , projects and project_user , to get automatically the values in the project_select table with the FK's? 如何使用php在表project_categoryprojectsproject_user中插入数据,以自动获取带有FK的project_select表中的值?

Update: How can I merge this 3 queries into one line? 更新:如何将这3个查询合并为一行?

INSERT INTO project_category
VALUES (1,'Fruits')

INSERT INTO projects
VALUES (4,'Apple')

INSERT INTO project_user
VALUES (2,'Adam')

and get this values with this one query in the project_select table: 在project_select表中通过此查询获得此值:

[project_select]
UserID (fk) | project_id (fk) | project_category_id (fk)
    2              4                  1

You can use the mysql_insert_id function to retrieve the id you just inserted. 您可以使用mysql_insert_id函数检索刚刚插入的ID。

mysql_query("INSERT INTO Persons VALUES (4,'Nilsen', 'Johan', 'Bakken 2', 'Stavanger')");
$person_id = mysql_insert_id();

So, do inserts on your tables, call mysql_insert_id() after each insert, store inserted IDs and finally use the IDs in the mysql command to create the join table. 因此,请在表上进行插入,在每次插入后调用mysql_insert_id(),存储插入的ID,最后在mysql命令中使用这些ID创建联接表。

I doubt that I understood your problem correctly. 我怀疑我正确理解了您的问题。 But if you want to have the values entered automatically in project_select table? 但是,是否要在project_select表中自动输入值? Then how about using MySql triggers? 那如何使用MySql触发器呢? But be sure you are well aware of the database internals before using it. 但是在使用数据库之前,请确保您对数据库的内部知识了如指掌。

What are triggers?, Setting up triggers 什么是触发器?,设置触发器

But, please describe this - 但是,请描述一下-

problem with foreign key insert? 外键插入问题?

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

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