正如手册中所提到的:
因此,
LAST_INSERT_ID()
(with no argument) returns aBIGINT
(64-bit) value representing the first automatically generated value that was set for anAUTO_INCREMENT
column by the most recently executedINSERT
statement to affect such a column. For example, after inserting a row that generates anAUTO_INCREMENT
value, you can get the value like this:
mysql>SELECT LAST_INSERT_ID(); ->195
The currently executing statement does not affect the value of
LAST_INSERT_ID()
. Suppose that you generate anAUTO_INCREMENT
value with one statement, and then refer toLAST_INSERT_ID()
in a multiple-rowINSERT
statement that inserts rows into a table with its ownAUTO_INCREMENT
column. The value ofLAST_INSERT_ID()
will remain stable in the second statement; its value for the second and later rows is not affected by the earlier row insertions. (However, if you mix references toLAST_INSERT_ID()
andLAST_INSERT_ID(expr)
, the effect is undefined.)If the previous statement returned an error, the value of
LAST_INSERT_ID()
is undefined. For transactional tables, if the statement is rolled back due to an error, the value ofLAST_INSERT_ID()
is left undefined. For manual ROLLBACK, the value ofLAST_INSERT_ID()
is not restored to that before the transaction; it remains as it was at the point of the ROLLBACK.
LAST_INSERT_ID()
始终是事务安全的(即使您不使用事务)。$dbh->beginTransaction();
2)插入代码 + lastInsertId()
3)$dbh->commit();
- Asaf回滚(rollback)
来撤销你所做的操作 :) - Rudi Visser
lastInsertId()
是由PDO驱动程序本身提供的,可能是一个实际的SQL查询语句,也可能不是。虽然这可能仍然完全正确,但仅凭这个还不够确定! - Rudi Visser