如何在连接值上选择最后插入的ID

时间:2013-10-01 03:01:22

标签: php mysql

我正在尝试获取多个插入行的最后插入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()没有价值。

2 个答案:

答案 0 :(得分:0)

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

您需要做的是先将其转换为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')";

答案 1 :(得分:0)

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

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

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()之后单独调用mysql_query()来检索上次插入的ID。然后在您作为第二个查询的参数时使用该值。

$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列。省略它。
  • 在代码中至少使用某种错误处理

旁注:考虑将prepared statementsmysqli_*PDO一起使用,而不是插入查询字符串并将其广泛用于sql注入