PHP mysql_insert_id() 函数


PHP mysql_insert_id() 函数

定义和用法

mysql_insert_id() 函数返回上一步 INSERT 操作产生的 ID。

如果上一查询没有产生 AUTO_INCREMENT 的 ID,则 mysql_insert_id() 返回 0。

语法

mysql_insert_id(connection)
参数 描述
connection 可选。规定 MySQL 连接。如果未规定,则使用上一个连接。

说明

mysql_insert_id() 返回给定的 connection 中上一步 INSERT 查询中产生的 AUTO_INCREMENT 的 ID 号。如果没有指定 connection ,则使用上一个打开的连接。

提示和注释

注释:如果需要保存该值以后使用,要确保在产生了值的查询之后立即调用 mysql_insert_id()。

实例

<?php$con = mysql_connect("localhost", "hello", "321");if (!$con)  {  die('Could not connect: ' . mysql_error());  }$db_selected = mysql_select_db("test_db",$con);$sql = "INSERT INTO person VALUES ('Carter','Thomas','Beijing')";$result = mysql_query($sql,$con);echo "ID of last inserted record is: " . mysql_insert_id();mysql_close($con);?>

输出类似:

ID of last inserted record is: 5
标签:, , ,