douhe2305 2013-10-16 19:31
浏览 405
已采纳

更可靠的LAST_INSERT_ID解决方案[重复]

This question already has an answer here:

so I want to link two tables with a common column "messageID". so first I insert into table 1 to get the Auto incremented id, then take that ID with LAST_INSERT_ID function and give that as the id for table 2:

$db->("INSERT INTO table_1 VALUES('','$message')");
$db->("INSERT INTO table_2 VALUES(LAST_INSERT_ID(),'$message');

but here's my concern, there might be two users running this script simultaneously, so in the few milliseconds between the two queries exicuting the LAST_INSERT_ID could have changed, so now the two id's are different. Is there any way I can prevent this possibility. I know it is not possible to insert into two tables with one query, which was my first thoughts. Any ideas much appreciated. Thank you

</div>
  • 写回答

2条回答 默认 最新

  • dsn46282 2013-10-16 19:33
    关注

    The LAST_INSERT_ID is local to the connection session, so it will not conflict with a different user making an insert.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?