MySQL returns the record ID after inserting the record

Source: Internet
Author: User

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

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.