This record ID is returned after a Mysql insert record

Source: Internet
Author: User
Tags mysql insert

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.