Recently and Sobin are doing a project for a boutique course, because a fixed ID is used as an association between tables, so after inserting data into the previous table, you pass the ID of the inserted data generation to the next table. Studied a decision to use MySQL to provide a last_insert_id () function. Liehuo.net
LAST_INSERT_ID () (with no argument) returns the automatically generated value, is set for a auto_increment col Umn by the most recently executed inserts or UPDATE statement to affect such a column. For example, after inserting a row that generates a Auto_increment value, you can get the value like this: |
Copy to Clipboard
Mysql> SELECT last_insert_id ();
-> 195
Simply put, this function will return the value of the field that the inserted record added to the table, and we generally name the self-added field as an ID. This allows you to return the ID value of the record you just inserted. Liehuo.net
A simple example:
Copy to Clipboard
$query = "INSERT into ' testtable ' (' clou1 ', ' clou2 ') VALUES (' TestValue ', ' Test ')";
mysql_query ($query);
$query = "Select last_insert_id ()";
$result =mysql_query ($query);
$rows =mysql_fetch_row ($result);
echo $rows [0];
This function is based on connection, which is not affected by the connection of other clients, so the result is accurate. If you use the Select Max (ID) from table, it is possible to go wrong under a high density insert request, returning an error value