2012-04-30 98 views
1

我想從TABLE1最新插件的價值添加到隨後的多個INSERT語句轉換成TABLE2其中包括多個條目 - 然而在MySQL中,我只是得到一個0(零)爲每個條目添加到TABLE2。如何在隨後的MULTIPLE插入語句中使用mysql_insert_id中的最新插入值(在PHP和MYSQL中)?

我知道我需要的mysql_insert_id存儲在一個變量的第一個MySQL查詢執行後。所以,我已經包括了第一mysql_query()聲明後立即叫$post_id變量,如下所示:

// If the submit button is pressed in the HTML form 
if (isset($_POST['submit_event'])) { 
    // First SQL Statement 
    if (!mysql_query($sql1,$con)) 
     { 
     die('Error: ' . mysql_error()); 
     } 
    echo "SQL 1 SUCCESS! 1 record added<br/>"; 

    // A variable to store the id from the last MySQL query 
    // This is the first time I have declared this variable 
    $post_id = mysql_insert_id(); 

    // Second SQL Statement which utilises the variable 
    if (!mysql_query($sql2,$con)) 
    { 
     die('Error: ' . mysql_error()); 
    } 
    echo "SQL 2 SUCCESS! 1 record added<br/>"; 
    echo "Finito!<br/>"; 
    mysql_close($con); 
} 

此SQL多重插入語句轉換成TABLE2我寫如下:

$sql2="INSERT INTO TABLE2 (post_id, meta_key, meta_value) 
    VALUES 
    ($post_id,'key 1','value 1'), 
    ($post_id,'key 2','value 2'), 
    ($post_id,'key 3','value 3') 
"; 

然而,儘管所有這一切(看起來是正確的),當我真的在MySQL中查看時,TABLE2中每個條目的post_id都是0(零)?

我要去哪裏錯了?幫幫我!

+2

'$ sql1'查詢內部有什麼? – vyegorov

+0

顯然'$ post_id' **是**'0',那麼你對此有何想法?請參閱http://php.net/mysql_insert_id。 – hakre

+0

$ SQL1什麼特別的,TABLE1包括AUTO_INCREMENT字段和如下:'$ SQL1 = 「INSERT INTO TABLE1(列1,列2,欄3)VALUES(1, 'DATA1', '數據2')」;' –

回答

0

我發現最終的答案!我意識到,因爲我在$post_id = mysql_insert_id();之前放置了$sql2字符串語句,所以PHP無法將其插入代碼中。所以正確的方法是:

// If the submit button is pressed in the HTML form 
if (isset($_POST['submit_event'])) { 
// First SQL Statement 
if (!mysql_query($sql1,$con)) 
    { 
    die('Error: ' . mysql_error()); 
    } 
echo "SQL 1 SUCCESS! 1 record added<br/>"; 

// A variable to store the id from the last MySQL query 
// This is the first time I have declared this variable 
$post_id = mysql_insert_id(); 

// Place the SQL statement AFTER the mysql_insert_id() variable 
$sql2="INSERT INTO TABLE2 (post_id, meta_key, meta_value) 
VALUES 
($post_id,'key 1','value 1'), 
($post_id,'key 2','value 2'), 
($post_id,'key 3','value 3') 
"; 

// Second SQL Statement which utilises the variable 
if (!mysql_query($sql2,$con)) 
{ 
    die('Error: ' . mysql_error()); 
} 
echo "SQL 2 SUCCESS! 1 record added<br/>"; 
echo "Finito!<br/>"; 
mysql_close($con); 
} 
0

這可能是一個愚蠢的問題,但從代碼中不清楚:您是否將$post_id值插入到$sql2字符串中?

$sql2="INSERT INTO TABLE2 (post_id, meta_key, meta_value) 
    VALUES 
    (" . $post_id . ",'key 1','value 1'), 
    (" . $post_id . ",'key 2','value 2'), 
    (" . $post_id . ",'key 3','value 3') "; 
+0

是的正確 - 我將$ post_id插入$ sql2字符串!我應該按照你上面寫的方式來做還是我的方式是一個同樣有效的例子? –

0
$sql2="INSERT INTO TABLE2 (post_id, meta_key, meta_value) 
    VALUES 
    ({$post_id},'key 1','value 1'), 
    ({$post_id},'key 2','value 2'), 
    ({$post_id},'key 3','value 3') 
";