Reputation: 5354
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 ?
Upvotes: 1
Views: 2342
Reputation: 1509
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.
Upvotes: 1
Reputation: 3042
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.
Upvotes: 2