mysql_insert_id() function in PHP

What is mysql_insert_id() function in PHP?
How does mysql_insert_id() works?

Explanation

The mysql_insert_id() function returns the AUTO_INCREMENT ID generated from the previous INSERT operation.
Syntax
int mysql_insert_id ( [resource link_identifier])

Returns ID generated for an AUTO_INCREMENT column by the previous INSERT query on success, 0 if the previous query does not generate an AUTO_INCREMENT value, or FALSE if no MySQL connection was established.
mysql_insert_id() returns the ID generated for an AUTO_INCREMENT column by the previous INSERT query using the given link_identifier. If link_identifier is not specified, the last opened link is assumed for connection.
Example

<?php
//Attempt to connect to the default database server
$link = mysql_connect("mysql_host", "mysql_user", "mysql_password")
or die ("Could not connect");
//select database
mysql_select_db('database',$link);
$query = "insert into my_table values('','Bill',2000,'Germany')";
//execute query
$result = mysql_query($query);
//print AUTO_INCREMENT ID generated from the previous INSERT operation
printf("Last inserted record has id :%dn", mysql_insert_id());
?>

RESULT:
Last inserted record has id : 10
See also: mysql_query().

PHP Topics


Ask Questions

Ask Question