PHP mysqli_stmt::$insert_id / mysqli_stmt_insert_id() 函数用于获取之前 INSERT 生成的 ID
语法
//面向对象风格
$mysqli_stmt->insert_id;
//面向过程风格
mysqli_stmt_insert_id(statement)
参数
statement | 必需。 仅适用于面向过程风格:指定 mysqli_stmt_init() 返回的 mysqli_stmt 对象。 |
返回值
返回 ID从之前的 INSERT 操作生成。
示例:面向对象风格
下面的示例显示了 mysqli_stmt::insert_id 属性的用法。
<?php
//建立与数据库的连接
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: ". $mysqli->connect_error;
exit();
}
//准备执行SQL语句
$query = "INSERT INTO Employee (Name, City, Salary) VALUES (?, ?, ?)";
$stmt = $mysqli->prepare($query);
$name = "John";
$city = "London";
$salary = 2800;
$stmt->bind_param('ssd', $name, $city, $salary);
//执行SQL语句
$stmt->execute();
//获取ID
$id = $stmt->insert_id;
printf("New record has ID %d.\n", $id);
//关闭连接
$mysqli->close();
?>
上述代码的输出将类似于:
New record has ID 1.
示例:面向过程风格
下面的示例显示mysqli_stmt_insert_id 的用法() 函数。
<?php
//建立与数据库的连接
$mysqli = mysqli_connect("localhost", "user", "password", "database");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: ". mysqli_connect_error();
exit();
}
//准备执行SQL语句
$query = "INSERT INTO Employee (Name, City, Salary) VALUES (?, ?, ?)";
$stmt = mysqli_prepare($mysqli, $query);
$name = "John";
$city = "London";
$salary = 2800;
mysqli_stmt_bind_param($stmt, 'ssd', $name, $city, $salary);
//执行SQL语句
mysqli_stmt_execute($stmt);
//获取ID
$id = mysqli_stmt_insert_id($stmt);
printf("New record has ID %d.\n", $id);
//关闭连接
mysqli_close($mysqli);
?>
上述代码的输出将类似于:
New record has ID 1.