将数据插入两个表?

时间:2010-09-20 09:37:39

标签: php mysql insert

我正在使用mysql,这是我拥有的两个表:

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

我想要做的是,如果帖子有#tag,我在POSTS表格中插入初始帖子,在post_tags表格中插入数据,我怎么能这样做呢?

P.S。我已经知道如何检查帖子是否有标签!!我只是想承担,如何将数据插入到两个!!特别是ID,因为它们是在mysql(autoincrement)中生成的!!

1 个答案:

答案 0 :(得分: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