简体   繁体   中英

How to automatically add a new row to another table PHP MYSQL

I have 2 tables that have one-to-one relationship in 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. Is there any mysql command or PHP script that I can use it ?

You might set up a TRIGGER in the database. These trigger entities are stored in the database's structure, with PHP you might only execute the CREATE TRIGGER query which creates one.

However, two tables having the exact same data as their PRIMARY KEY sounds like your database structure is a bit badly modelled. 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:

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.

$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.

This could of course be risky if many rows are inserted at the same time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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