Recently, Sobin is working on a high-quality course project, because a fixed id is used as the association between tables, therefore, after inserting data in the previous table, you must pass the auto-increment id generated by the inserted data to the next table. I studied how to use Mysql to provide a LAST_INSERT_ID () function. Liehuo.net
LAST_INSERT_ID () (with no argument) returns the first automatically generated value that was set for an AUTO_INCREMENT column by the most recently executed INSERT or UPDATE statement to affect such a column. for example, after inserting a row that generates an AUTO_INCREMENT value, you can get the value like this: |
Veryhuo.com
Copy to ClipboardReference: [www.bkjia.com] mysql> SELECT LAST_INSERT_ID ();
-> 195
Simply put, this function returns the value of the Field automatically added to the inserted record in the table. Generally, we name the auto-increment field as ID. In this way, the ID value of the newly inserted record can be returned. Liehuo.net
A simple example: liehuo.net
Copy to ClipboardReference: [www.bkjia.com] $ 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, that is, it will not be affected by connections from other clients, so the result is accurate. If select max (id) from table is used, problems may occur in high-density insert requests. The error value liehuo.net is returned.