[英]How to automatically add a new row to another table PHP MYSQL
I have 2 tables that have one-to-one relationship in mySQL. 我有两个在mySQL中具有一对一关系的表。 they both have the same user_id as Primary key, and I need somehow when I insert a post into the my first table, automatically be able to insert the row with same user_id to my second table.
它们都具有与主键相同的user_id,并且当我将帖子插入到我的第一个表中时,我需要以某种方式,自动能够将具有相同user_id的行插入到我的第二个表中。 Is there any mysql command or PHP script that I can use it ?
有没有我可以使用的mysql命令或PHP脚本?
You might set up a TRIGGER
in the database. 您可以在数据库中设置
TRIGGER
。 These trigger entities are stored in the database's structure, with PHP you might only execute the CREATE TRIGGER
query which creates one. 这些触发器实体存储在数据库的结构中,使用PHP,您可能只执行创建一个的
CREATE TRIGGER
查询。
However, two tables having the exact same data as their PRIMARY KEY
sounds like your database structure is a bit badly modelled. 但是,两个表与
PRIMARY KEY
具有完全相同的数据听起来就像您的数据库结构有点严重建模。 You should take time to remodel the database, essentially merging (if possible) the two tables together. 您应该花时间重新构建数据库,基本上将两个表合并(如果可能)。
And if you are using PHP to INSERT INTO
the database, you can call the two queries after each other: 如果您使用PHP来
INSERT INTO
数据库,您可以在彼此之后调用两个查询:
INSERT INTO table1(field1, field2...) VALUES (value1, value2...)
INSERT INTO table2(field1, field2...) VALUES (value1, value2...)
But reliance on two queries after each other requires pinpoint accuracy as the primary keys might go out of sync, breaking the relations. 但是,相互依赖两个查询需要精确定位,因为主键可能不同步,破坏了关系。
If I understand your question right you can get the inserted user_id from the first table and use that to insert a new row in the second table. 如果我理解你的问题,你可以从第一个表中获取插入的user_id,并使用它在第二个表中插入一个新行。
$query = mysql_query("SELECT * FROM first_table ORDER BY user_id DESC LIMIT 1");
$row = mysql_fetch_assoc($query);
Now $row['user_id'] can be inserted in the second table. 现在可以在第二个表中插入$ row ['user_id']。
This could of course be risky if many rows are inserted at the same time. 如果同时插入许多行,这当然会有风险。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.