mysql重用自动增量id
I have the following situation,I simplified the table to keep things readable here.
Table structure: (note: id
is auto-increment
)
columns : id,text,rid
Based on the input of a form, 2 rows are being inserted into a table.
INSERT INTO tablename (id,text,rid)
VALUES (NULL, $usertext1, ??),(NULL, $usertext2, ??)
Now, Where is my problem's at ?
I need the first ?? and the second ?? to be the same int, and Both need to be the auto-increment id from the first insert! I tried LAST_INSERT_ID() but it returned 0.
The result how I'd like to have it :
1 | abctext | 1
2 | lalala | 1
3 | fajoif | 2
4 | oijgoi | 2
Any help would be highly appreciated :)
Thanks.
我有以下情况,我简化了表格,以便在这里保持可读性。 p>
表格结构 strong>(注意: 列: strong> 根据表单的输入,将2行插入表中。 p>
现在,我的问题在哪里? p>
我需要第一个? 和第二个? 是 int strong>,两者都需要是第一次插入的自动增量 strong> ID! 我尝试了 LAST_INSERT_ID() strong>,但它返回 0 strong>。 p>
结果我想得到它: p>
1 | abctext | 1 p>
2 | 拉拉| 1 p>
3 | fajoif | 2 p>
4 | oijgoi | 2 p>
任何帮助都将受到高度赞赏:) p>
谢谢。 p>
div> id code>是
自动增量 code>) p>
id,text,rid code> p>
INSERT INTO tablename(id,text,rid)
VALUES(NULL,$ usertext1,??),(NULL,$ usertext2,??)
code> pre>
you have to follow something like this to get it done:
<?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);