PHP mysqli insert_id() 函数
示例 - 面向对象的样式
假设 Persons 表有一个自动生成的 ID 字段。返回最后一次查询中的 ID:
<?php
$mysqli = new mysqli("localhost","my_user","my_password","my_db");
if ($mysqli -> connect_errno) {
echo "Failed to connect to MySQL: " . $mysqli -> connect_error;
exit();
}
$mysqli -> query("INSERT INTO Persons (FirstName, LastName, Age) VALUES ('Glenn', 'Quagmire', 33)");
// Print auto-generated id
echo "New record has id: " . $mysqli -> insert_id;
$mysqli -> close();
?>
$mysqli = new mysqli("localhost","my_user","my_password","my_db");
if ($mysqli -> connect_errno) {
echo "Failed to connect to MySQL: " . $mysqli -> connect_error;
exit();
}
$mysqli -> query("INSERT INTO Persons (FirstName, LastName, Age) VALUES ('Glenn', 'Quagmire', 33)");
// Print auto-generated id
echo "New record has id: " . $mysqli -> insert_id;
$mysqli -> close();
?>
查看底部的程序样式示例。
定义和用法
mysqli_insert_id() 函数返回最后一个查询中自动生成的 ID(通过 AUTO_INCREMENT 生成)。
语法
面向对象的风格:
$mysqli ->
insert_id
程序风格:
mysqli_insert_id(connection)
参数值
参数 | 描述 |
---|---|
connection | 必需。规定要使用的 MySQL 连接。 |
技术细节
返回值: | 返回一个在最后一个查询中自动生成的带有 AUTO_INCREMENT 字段值的整数。如果数字 > 最大整数值,它将返回一个字符串。如果没有更新或没有 AUTO_INCREMENT 字段,将返回 0。 |
---|---|
PHP 版本: | 5+ |
示例 - 程序样式
假设 Persons 表有一个自动生成的 ID 字段。返回最后一次查询中的 ID:
<?php
$con = mysqli_connect("localhost","my_user","my_password","my_db");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
mysqli_query($con, "INSERT INTO Persons (FirstName, LastName, Age) VALUES ('Glenn', 'Quagmire', 33)");
// Print auto-generated id
echo "New record has id: " . mysqli_insert_id($con);
mysqli_close($con);
?>
$con = mysqli_connect("localhost","my_user","my_password","my_db");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
mysqli_query($con, "INSERT INTO Persons (FirstName, LastName, Age) VALUES ('Glenn', 'Quagmire', 33)");
// Print auto-generated id
echo "New record has id: " . mysqli_insert_id($con);
mysqli_close($con);
?>