2011-01-26 83 views
1

我嘗試給我一個真正的問題的anology。我有兩個表格,一個用於評論。每個人都有自己的主鍵。但是每篇文章都可以有幾條評論。將值插入兩個相關的表

因此,這裏是SQL用於插入文章到數據庫(MySQL的在PHP)代碼:

$sql="INSERT INTO articles (content) 
     VALUES 
     ('$content')";//$content variable has text related to the article 

的物品表有兩項條款ArticleID和內容。當我插入內容時,每個插入的文章會自動獲得一個獨特的articleId。 articleId是文章表的主鍵。有沒有一種簡單的方法以有效的方式獲得該文章的編號?我的意思是有效的方法:儘量避免更多的SQL代碼。因爲在下一步中,我需要使用articleId將每條評論與這篇文章相關聯。

$sql="INSERT INTO comments (comment, articleId) 
     VALUES 
     ('$comment', '$articleId')";//commentId is the primary key, but it's auto inserted 

回答

3

爲什麼不是這樣的東西這個:

$query = "INSERT INTO articles ..." 
mysql_query($query); 
$new_id = mysql_insert_id(); 

foreach($comments as $comment) { 
    $query = "INSERT INTO comments (articleID, comment) VALUES ($new_id, $comment);" 
    mysql_query($query); 
} 
0

嘗試實施觸發器,以便在文章獲取插入時執行插入操作。

+0

我不明白?你能給som代碼例子嗎? – einstein 2011-01-26 18:04:56

0

觸發器似乎是要走的路 - 但是,不要太觸發快樂,因爲邏輯和觸發器本身是隱藏的使用。

總是在某個地方記錄一個您創建的觸發器,以防萬一您忘記了它的更遠行。

+0

我不知道觸發器是什麼?代碼示例? – einstein 2011-01-26 18:07:23

0

在您的第二個查詢中,您可以引用最後一個插入ID - 您可以使用MySQL函數或PHP函數來執行此操作。

的MySQL:

INSERT INTO comments (comment, articleId) 
     VALUES 
     ('comment', LAST_INSERT_ID()) 

PHP:

$sql="INSERT INTO comments (comment, articleId) " 
     . "VALUES " 
     . "('$comment', mysql_insert_id())"; 

編輯:如果您正在創建一個條款ArticleID之後插入一個以上的評論,你會想,只要你插入存儲條款ArticleID (在PHP中),然後在將來使用該變量,如下所示:

$sql="INSERT INTO articles (content) 
     VALUES 
     ('$content')" 
$articleid = mysql_insert_id(); 

$sql="INSERT INTO comments (comment, articleId) " 
     . "VALUES " 
     . "('$comment', $articleid)"; 
$sql="INSERT INTO comments (comment, articleId) " 
     . "VALUES " 
     . "('$comment', $articleid)"; 
+0

如果有超過1條評論要插入,這將炸燬 - 之後last_insert_id()將返回先前評論的ID,而不是文章的ID。 – 2011-01-26 18:08:36