The code is as follows |
Copy Code |
MYSQL_INSERT_ID () The mysql_insert_id () function returns the ID generated by the previous insert operation. If the previous query does not produce a auto_increment ID, mysql_insert_id () returns 0. |
Syntax: mysql_insert_id (Connection)
parameter connection, optional. Specify the MySQL connection. If not specified, the previous connection is used.
MYSQL_INSERT_ID () returns the ID number of the auto_increment generated in the previous insert query in the given connection. If connection is not specified, the previous open connection is used.
If you need to save this value later, make sure to call MYSQL_INSERT_ID () immediately after the query that generated the value.
code is as follows |
copy code |
<?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 the person VALUES (' Carter ', ' Thomas ', ' Beijing ')"; $result = mysql_query ($sql, $con); Echo ID of last inserted the record is:. MYSQL_INSERT_ID (); Mysql_close ($con); ? |
MYSQL_INSERT_ID () returns the ID number of the auto_increment generated in the previous insert query in the given link_identifier. If Link_identifier is not specified, the previous open connection is used. If the previous query does not produce a auto_increment value, mysql_insert_id () returns 0. If you need to save this value later, make sure to call MYSQL_INSERT_ID () immediately after the query that generated the value.
LAST_INSERT_ID ()
MySQL also provides an API with the same functionality that always holds the most recent auto_increment values and is not reset between query statements, that is, after the insert operation, execute SELECT, UPDATE, The DELETE statement does not affect the return value of the API.
You can use SELECT last_insert_id (); To query for the return value of last_insert_id ().
Inserting multiple records with a single INSERT statement, LAST_INSERT_ID () returns only the Auto_increment value produced by the first record inserted.