簡體   English   中英

如何在串聯值中選擇最后插入的ID

[英]How to select the last inserted ID on concatenated values

我正在嘗試獲取多個插入行的最后一個插入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()沒有值。

除非我誤讀了您的代碼,否則您是在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')";

您正在混合php函數mysql_insert_id()和SQL INSERT語句語法。

無論是使用MySQL函數LAST_INSERT_ID()VALUES子句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_query()之后立即單獨調用mysql_insert_id()來檢索最后插入的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列。 只是忽略它。
  • 在代碼中至少使用某種錯誤處理

附帶說明 :與其插入查詢字符串,而不是讓它對sql-injections開放, mysqli_*考慮將准備好的語句mysqli_*PDO

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM