PHP mysqli_insert_id() 函数可用于获取由 INSERT 或 UPDATE 语句在具有 AUTO_INCRMENT 属性的列的表上生成的 ID。对于多行 INSERT 语句,它返回成功插入的第一个自动生成的值。
获取最后一个 ID - 面向对象风格
考虑一个名为 Employee 包含四列:EmpID、Name、City 和 Salary。该表的EmpID列是一个AUTO_INCRMENT字段。
CREATE TABLE Employee (
EmpID INT AUTO_INCREMENT PRIMARY KEY,
Name VARCHAR(255) NOT NULL,
City VARCHAR(100),
Salary DECIMAL(18,2)
);
假设该表当前没有记录。下面的示例演示了如何使用面向对象的风格执行插入操作后获取最后一个 id。
<?php
//建立与数据库的连接
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: ". $mysqli->connect_error;
exit();
}
//插入第一条记录
$query = "INSERT INTO Employee (Name, City, Salary) VALUES ('John', 'London', 2800)";
$mysqli->query($query);
//获取最后一个插入id
printf("New record has ID %d.\n", $mysqli->insert_id);
//插入两条记录
$query = "INSERT INTO Employee (Name, City, Salary) VALUES ('Marry', 'Paris', 2750)";
$mysqli->query($query);
$query = "INSERT INTO Employee (Name, City, Salary) VALUES ('Jo', 'Amsterdam', 2900)";
$mysqli->query($query);
//获取最后一个插入id
printf("New record has ID %d.\n", $mysqli->insert_id);
//关闭连接
$mysqli->close();
?>
上述代码的输出将是:
New record has ID 1.
New record has ID 3.
获取最后一个 ID - 程序样式
使用以下脚本的过程样式可以实现相同的效果:
<?php
//建立与数据库的连接
$mysqli = mysqli_connect("localhost", "user", "password", "database");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: ". mysqli_connect_error();
exit();
}
//插入第一条记录
$query = "INSERT INTO Employee (Name, City, Salary) VALUES ('John', 'London', 2800)";
mysqli_query($mysqli, $query);
//获取最后一个插入id
printf("New record has ID %d.\n", mysqli_insert_id($mysqli));
//插入两条记录
$query = "INSERT INTO Employee (Name, City, Salary) VALUES ('Marry', 'Paris', 2750)";
mysqli_query($mysqli, $query);
$query = "INSERT INTO Employee (Name, City, Salary) VALUES ('Jo', 'Amsterdam', 2900)";
mysqli_query($mysqli, $query);
//获取最后一个插入id
printf("New record has ID %d.\n", mysqli_insert_id($mysqli));
//关闭连接
mysqli_close($mysqli);
?>
上述代码的输出将是:
New record has ID 1.
New record has ID 3.
完整 PHP MySQLi 参考
有关 PHP MySQLi 扩展的所有属性、方法和功能的完整参考,请参阅 PHP MySQLi 参考。