定义
mysqli_insert_id()函数返回在上次查询中使用的id(使用AUTO_INCREMENT生成)。
语法
面向对象的风格:
mixed $mysqli->insert_id;
程序风格:
mixed mysqli_insert_id(mysqli $link)
参数
参数
是否必需
说明
link
需要。
MySQL连接使用
返回值
它返回由最后一个查询更新的AUTO_INCREMENT字段的值。
如果没有更新或没有AUTO_INCREMENT字段,则返回零。
实例1
Employee表具有自动生成的id字段。以下代码获取上次查询中使用的ID。
// http://www.manongjc.com/article/1680.html
// 作者:码农教程
$con=mysqli_connect("localhost","my_user","my_password","my_db");
if (mysqli_connect_errno($con)){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"INSERT INTO Employee (name) VALUES('PHP')");
// Print auto-generated id
echo "New record has id: " . mysqli_insert_id($con);
mysqli_close($con);
?>
实例2
// http://www.manongjc.com/article/1680.html
// 作者:码农教程
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$mysqli->query("CREATE TABLE myCity LIKE City");
$query = "INSERT INTO myCity (name)VALUES ('New York')";
$mysqli->query($query);
printf ("New Record has id %d.\n", $mysqli->insert_id);
$mysqli->query("DROP TABLE myCity");
$mysqli->close();
?>