我遇到以下情况,我简化了表格以保持此处的可读性。
表结构:(注:id
为自增
)
列: id,text,rid
根据表单的输入,将 2 行插入到表中。
INSERT INTO tablename (id,text,rid)
VALUES (NULL, $usertext1, ??),(NULL, $usertext2, ??)
现在,我的问题出在哪里?
我需要第一个?第二个?是相同的int,并且两者都需要是第一次插入的自动增量 id!我尝试了LAST_INSERT_ID(),但它返回了0。
我想要的结果:
1 |抽象文本 | 1
2 |拉拉拉 | 1
3 |法茹伊夫 | 2
4 |奥伊戈伊 | 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);
关于php - mysql重用自动递增id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29773235/