1

I want to add the value of the latest insert from TABLE1 to a subsequent MULTIPLE insert statement into TABLE2 which includes multiple entries - however in MySQL I am just getting a 0 (zero) for each entry added into TABLE2.

I know I need to store the mysql_insert_id in a variable after the first MySQL query has been executed. So I have included a variable called $post_id right after the first mysql_query() statement as follows:

// 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);
}

This SQL multiple insert statement into TABLE2 I have written is as follows:

$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')
";

However, in spite of all of this (which looks correct) when I ACTUALLY look in MySQL, the post_id for EVERY entry in TABLE2 comes out as 0 (zero)?

Where am I going wrong?! HELP!

4

3 回答 3

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')
";
于 2012-05-01T18:37:35.707 回答
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') "; 
于 2012-04-30T12:10:57.550 回答
0

我终于找到了答案!我意识到,因为我在PHP$sql2之前放置了字符串语句,$post_id = mysql_insert_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();

// 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);
}
于 2012-05-07T20:14:01.917 回答