2012-04-12 96 views
0

我想爲我的網站創建一個基本論壇。 我對這個2個表:在2表中插入值,其中第2表需要第1表中的ID

表主題:域ID,標題

表的帖子:當用戶想對創建一個話題,他必須完成一個表單域ID,topicid,消息

與主題標題和消息。標題將被插入到主題表格和帖子表格中的消息中,但是我將需要第二個插入的topicid(主題表格中的字段標識)。

INSERT INTO topics (title) VALUES ('$title') 
INSERT INTO posts (topicid, message) VALUES ('???', '$message') 

如何獲取topicid?

回答

2

MySQL的:

INSERT INTO topics (title) VALUES ('$title') 
INSERT INTO posts (topicid, message) VALUES (LAST_INSERT_ID(), '$message') 

或者用PHP:

[...] 
// Connect to mysql 
$title = 'Foo'; 
$message = 'Bar'; 

mysql_query('INSERT INTO topics (title) VALUES (' . $title . ')'); 
mysql_query('INSERT INTO posts (topicid, message) VALUES (' . mysql_insert_id() . ', ' . $message . ')'); 
相關問題