检索带有AUTO_INCREMENT列的表上的插入查询生成的最后一个ID。
面向对象风格
$id = $conn->insert_id;
程序风格
$id = mysqli_insert_id($conn);
如果连接上没有先前的查询,或者该查询未更新AUTO_INCREMENT值,则返回零。
更新行时插入ID
通常,一条UPDATE语句不返回插入ID,因为AUTO_INCREMENT仅在保存(或插入)新行后才返回ID。对新ID进行更新的一种方法是使用INSERT ... ON DUPLICATE KEY UPDATE语法进行更新。
设置以下示例:
CREATE TABLE iodku ( id INT AUTO_INCREMENT NOT NULL, name VARCHAR(99) NOT NULL, misc INT NOT NULL, PRIMARY KEY(id), UNIQUE(name)) ENGINE=InnoDB; INSERT INTO iodku (name, misc) VALUES ('Leslie', 123), ('Sally', 456); Records: 2 Duplicates: 0 Warnings: 0 +----+--------+------+ | id | name | misc | +----+--------+------+ | 1 | Leslie | 123 | | 2 | Sally | 456 | +----+--------+------+
IODKU执行“更新”并LAST_INSERT_ID()检索相关信息的情况id:
$sql = "INSERT INTO iodku (name, misc) VALUES ('Sally', 3333) -- should update ON DUPLICATE KEY UPDATE -- `name` will trigger "duplicate key" id = LAST_INSERT_ID(id), misc = VALUES(misc)"; $conn->query($sql); $id = $conn->insert_id; -- picking up existing value (2)
IODKU执行“插入”并LAST_INSERT_ID()检索新的情况id:
$sql = "INSERT INTO iodku (name, misc) VALUES ('Dana', 789) -- Should insert ON DUPLICATE KEY UPDATE id = LAST_INSERT_ID(id), misc = VALUES(misc); $conn->query($sql); $id = $conn->insert_id; -- picking up new value (3)
结果表内容:
SELECT * FROM iodku; +----+--------+------+ | id | name | misc | +----+--------+------+ | 1 | Leslie | 123 | | 2 | Sally | 3333 | -- IODKU changed this | 3 | Dana | 789 | -- IODKU added this +----+--------+------+