2010-09-20 28 views
1

IM,這是兩個表我有:將數據插入兩個表中?用mysql

posts {id, user_id, post, date} 
post_tags {id, tag, post_id(references id in post), user_id} 

什麼即時試圖做的是後話了具有#tag,我插在POSTS表INTIAL職位,並在post_tags數據桌子,我怎麼能這樣做simlateanously?

P.S.我已經知道如何檢查帖子是否有標籤!我只想進行一下,如何將數據插入兩者!特別是ID,因爲它們是在mysql(autoincrement)中生成的!

回答

2

你可以分開這兩個查詢並且在彼此之後運行它們。您可以在表中使用mysql_insert_id()作爲最後插入的ID。

$query = "INSERT INTO posts (id, user_id, post, date) 
    VALUES (id, user_id, post, date)"; 
mysql_query($query) or die(mysql_error().$query); // run query 

$lastid = mysql_insert_id(); // this will get the last inserted id. 

$query = "INSERT INTO post_tags (id, tag, post_id, user_id) 
    VALUES (id, tag, ".$lastid.", user_id)"; 
mysql_query($query) or die(mysql_error().$query); // run query 
相關問題