Mysql_insert_id () returns the auto_increment ID generated in the previous insert query in the given link_identifier. If link_identifier is not specified, the last opened connection is used.
If no auto_increment value is generated in the previous query, mysql_insert_id () returns 0. If you want to save the value and use it later, make sure that mysql_insert_id () is called immediately after the query that generates the value ().
Note: The SQL function last_insert_id () in MySQL always saves the newly generated auto_increment value and is not reset between Query statements.
Example:
<? PHP
Mysql_connect ("localhost", "mysql_user", "mysql_password") or
Die ("cocould not connect:". mysql_error ());
Mysql_select_db ("mydb ");
Mysql_query ("insert into mytable (product) values ('kossu ')");
Printf ("the last inserted ID is". mysql_insert_id ());
?>
Supplement:
The mysql_insert_id () function returns the auto_increment ID generated from the previous insert operation.
The function mysql_insert_id () is used to obtain the ID generated by the previous insert operation.
This function returns 0 if the previous operation does not generate an auto_increment ID, or false on MySQL connection failure.
If the previous operation does not generate an automatically added ID [auto_increment id], the function returns 0. If the MySQL connection fails, false is returned.
Syntax
Syntax
Mysql_insert_id (connection)
Parameter Parameters |
Description |
Connection |
Optional. specifies the MySQL connection. If not specified, the last connection opened by mysql_connect () or mysql_pconnect () is used. Optional. Specify the MySQL connection. If this parameter is not specified, the last connection opened through mysql_connect () function or mysql_pconnect () function is used by default. |
Tips and notes
Notes
Note: Be sure to call mysql_insert_id () immediately after a query to get the correct value.
Note: You must be sure that you have requested the mysql_insert_id () function after a query statement to obtain the correct value.
Example
Case
<? PHP $ con = mysql_connect ("localhost", "Peter", "ABC123"); If (! $ Con) {die ('could not connect: '. mysql_error ());} $ Db_selected = mysql_select_db ("test_db", $ con ); $ SQL = "insert into person values ('B? Rge', 'referns', 'sandes', '17') "; $ result = mysql_query ($ SQL, $ con); echo" id of last inserted record is :". mysql_insert_id ()); Mysql_close ($ con);?> |
The output of the CODe above cocould be:
The above code will output the following results:
ID of last inserted record is: 5 |