dongzhu3548 2015-04-21 13:12
浏览 47
已采纳

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.

  • 写回答

1条回答 默认 最新

  • dsijovl015728613 2015-04-21 13:41
    关注

    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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)