0

我正在尝试获取多个插入行的最后插入 id。

record_id 是自动递增的

$sql = "INSERT INTO records (record_id, user_id, status, x) values ";
         $varray = array();

        $rid = $row['record_id'];
        $uid =  $row['user_name'];
        $status =  $row['status'];
        $x =  $row['x'];

        $varray[] = "('$rid', '$uid', '$status', '$x')";

       $sql .= implode(',', $varray);

      mysql_query($sql); 

      $sql2 = "INSERT INTO status_logs (id, record_id, status_id, date, timestamp, notes, user_id, x) VALUES";

      $varray2[] = "(' ', mysql_insert_id(), '$status', '$uid', '$x')";

      $sql2 .= implode(',', $varray2);

       mysql_query($sql2); 

这是结果:

INSERT INTO records (record_id, user_id,  notes, x) values ('', '1237615', 'this is a note', 'active')

INSERT INTO status_logs (log_id, record_id, status_id, date, timestamp, notes, user_id, x) VALUES('', INSERT INTO records (record_id, user_id,  notes, x) values ('', '1237615', 'this is a note', 'active')

INSERT INTO status_logs (log_id, record_id, status_id, date, timestamp, notes, user_id, x) VALUES('', mysql_insert_id(), '1', '2013:05:16 00:00:01', '', this is a note'', '1237615', 'active'), '1', '2013:05:16 00:00:01', '', this is a note'', '1237615', 'active')

没有任何价值mysql_insert_id()

4

2 回答 2

0

除非我误读了您的代码,否则您是mysql_insert_id从 SQL 中调用 PHP 函数吗?

您需要做的是首先将其抓取到 PHP 变量中,然后在 SQL 中使用该变量。像这样的东西:

// Run the first query
 mysql_query($sql); 

// Grab the newly created record_id
$recordid= mysql_insert_id();

然后在第二个 INSERT 中使用:

$varray2[] = "(' ', $recordid, '$status', '$uid', '$x')";
于 2013-10-01T03:34:06.273 回答
0

您正在混合使用 php 函数mysql_insert_id()和 SQLINSERT语句语法。

LAST_INSERT_ID()在语句的子句VALUES使用MySQL 函数INSERT

INSERT INTO records (user_id,  notes, x) VALUES('1237615', 'this is a note', 'active');
INSERT INTO status_logs (record_id, status_id, date, timestamp, notes, user_id, x)
VALUES(LAST_INSERT_ID(), '1', ...);
      ^^^^^^^^^^^^^^^^^

或者mysql_insert_id()通过在 first 之后单独调用来检索最后插入的 id mysql_query()。然后在您作为第二个查询的参数时使用该值。

$sql = "INSERT INTO records (user_id, ...) 
        VALUES(...)";
$result = mysql_query($sql); 
if (!$result) {
    die('Invalid query: ' . mysql_error()); //TODO beter error handling
}
$last_id = mysql_insert_id();
//         ^^^^^^^^^^^^^^^^^^

$sql2 = "INSERT INTO status_logs (record_id, ...) 
         VALUES $last_id, ...)";
$result = mysql_query($sql); 
if (!$result) {
    die('Invalid query: ' . mysql_error()); //TODO beter error handling
}

笔记:

  • 您不需要在列列表中指定 auto_incremented 列。只是省略它。
  • 在代码中至少使用某种错误处理

附带说明:与其对查询字符串进行插值并让其对 sql-injections 敞开大门,不如考虑使用带有or的准备好的语句mysqli_*PDO

于 2013-10-01T03:41:11.703 回答