2012-04-30 99 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') 
";