PHP/MySQL 插入行然后获取'id' [英] PHP/MySQL insert row then get 'id'
问题描述
当我插入一行时,我的表的 'id' 字段会自动增加.我想插入一行然后获取该 ID.
我会像我说的那样做,但是有没有一种方法可以让我不用担心插入行和获取 id 之间的时间?
我知道我可以在数据库中查询与输入的信息相匹配的行,但有很大的变化,会有重复,唯一的区别是 id.
$link = mysqli_connect('127.0.0.1', 'my_user', 'my_pass', 'my_db');mysqli_query($link, 插入到 mytable (1, 2, 3, 'blah')");$id = mysqli_insert_id($link);
无论您做什么,都不要插入然后执行SELECT MAX(id) FROM mytable
".就像你说的,这是一个竞争条件,没有必要.mysqli_insert_id()
已经有这个功能了.
另一种方法是一次性运行两个查询,并使用 MySQL
的 LAST_INSERT_ID()
方法,其中两个表同时修改(而 PHP 会不需要任何 ID),例如:
mysqli_query($link, "INSERT INTO my_user_table ...;INSERT INTO my_other_table (`user_id`) VALUES (LAST_INSERT_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.
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?
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);
See 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.
Another way would be to run both queries in one go, and using MySQL
's LAST_INSERT_ID()
method, where both tables get modified at once (and PHP does not need any ID), like:
mysqli_query($link, "INSERT INTO my_user_table ...;
INSERT INTO my_other_table (`user_id`) VALUES (LAST_INSERT_ID())");
Note that Each connection keeps track of ID separately (so, conflicts are prevented already).
这篇关于PHP/MySQL 插入行然后获取'id'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!