PHP/MySQL插入行,然后获取"id" [英] PHP/MySQL insert row then get 'id'
问题描述
当我插入一行时,表的'id'字段会自动增加.我要插入一行,然后获取该ID.
The 'id' field of my table auto increases when I insert a row. I want to insert a row and then get that ID.
我会按照我说的去做,但是有没有办法我不用担心插入行和获取ID之间的时间呢?
I would do it just as I said it, but is there a way I can do it without worrying about the time between inserting the row and getting the id?
我知道我可以在数据库中查询与输入的信息匹配的行,但是变化很大,会有重复项,唯一的区别是id.
I know I can query the database for the row that matches the information that was entered, but there is a high change there will be duplicates, with the only difference being the id.
推荐答案
$link = mysqli_connect('127.0.0.1', 'my_user', 'my_pass', 'my_db');
mysqli_query($link, "INSERT INTO mytable (1, 2, 3, 'blah')");
$id = mysqli_insert_id($link);
请参见 mysqli_insert_id()
.
无论您做什么,都不要插入然后执行"SELECT MAX(id) FROM mytable
".就像您说的那样,这是比赛条件,没有必要. mysqli_insert_id()
已经具有此功能.
Whatever you do, don't insert and then do a "SELECT MAX(id) FROM mytable
". Like you say, it's a race condition and there's no need. mysqli_insert_id()
already has this functionality.
这篇关于PHP/MySQL插入行,然后获取"id"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!