我正在尝试获取多个插入行的最后插入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()
没有价值。
答案 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
}
注意:
旁注:考虑将prepared statements与mysqli_*
或PDO
一起使用,而不是插入查询字符串并将其广泛用于sql注入