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 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用