繁体   English   中英

如何在后续的MULTIPLE插入语句(在PHP和MYSQL中)中使用mysql_insert_id的最新插入中的值?

[英]How do I use the value from the latest insert using mysql_insert_id in subsequent MULTIPLE insert statements (in PHP and MYSQL)?

我想将来自TABLE1的最新插入值添加到包含多个条目的TABLE2中的后续MULTIPLE插入语句中-但是在MySQL中,对于添加到TABLE2中的每个条目,我只会得到0(零)。

我知道在执行第一个MySQL查询后,需要将mysql_insert_id存储在变量中。 因此,我在第一个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);
}

我在TABLE2中编写的此SQL多重插入语句如下:

$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中EVERY条目的post_id都显示为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') "; 
$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')
";

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM