[英]mysql re-use auto increment id
我有以下情況,我簡化了表格以使內容易於閱讀。
表結構:(注意: id
是auto-increment
)
欄: id,text,rid
根據表單的輸入,將2行插入到表中。
INSERT INTO tablename (id,text,rid)
VALUES (NULL, $usertext1, ??),(NULL, $usertext2, ??)
現在,我的問題在哪里?
我需要第一個?? 第二個?? 是相同的int ,並且兩者都必須是第一次插入時的自動增量 ID! 我嘗試了LAST_INSERT_ID(),但返回0 。
結果我想擁有它:
1 | abctext | 1個
2 | 拉拉拉| 1個
3 | fajoif | 2
4 | oijgoi | 2
任何幫助將不勝感激:)
謝謝。
您必須遵循以下步驟才能完成:
<?php
$i=0;
$firstInsertId=0;
foreach($post as $value){// suppose each $post index contains the one complete post data
$usertxt=$value['text'];
$sql="INSERT INTO tablename (id,text,rid)
VALUES (NULL, $usertxt,$firstInsertId)";
$mysqli->query(sql);
if($i == 0)//flag to get first inserted Id
$firstInsertId=$mysqli->insert_id;
$i++;
}
$sql="update tablename set rid=$firstInsertId where id=$firstInsertId";
$mysqli->query(sql);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.