dsf12313 2016-02-09 16:53
浏览 17
已采纳

如何在mysql中插入2个相关记录

i want to store 2 related record in 2 different table in mysql
i have these information
name, option1, option2

name and its id are store in users table and options are store in options table
the uid in this table is auto increment

users table

uid --- name
1   --- Jack
2   --- Sara

options table

user_uid --- option
1        --- aaa
1        --- bbb
2        --- ccc
2        --- ddd

the question is how can i find next uid in users table to save my options with that foreign key, there are several ways to get next generated id like

LAST_INSERT_ID() 

or

mysql_insert_id()

or

$result = mysql_query("SHOW TABLE STATUS LIKE 'table_name'");
$row = mysql_fetch_array($result);
$nextId = $row['Auto_increment']; 

but if several request coming to server in same time are these ways work ?
what if after i get last id, another record saved to db and change last id
is there any way to reserve next auto increment id and get that ?

  • 写回答

1条回答 默认 最新

  • douweicheng5532 2016-02-09 17:23
    关注

    Apart from the fact that mysql functions are deprecated and removed in PHP 7, the mysql_insert_id will work just fine, since that the function returns the last generated id using your connection. In case another record is created by someone else, then you will get the last generated id using your connection and not the last inserted id into that table.

    Try using PDO or MySQLi instead.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥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 库的使用