PHP Gets the ID value of MySQL insert data

Source: Internet
Author: User
Tags mysql insert
  1. mysql_query ("SELECT Max (ID) from T1", $link);
Copy Code

Using this method gives the highest ID value, which is the last value, but when a multilink thread, this maximum ID is not necessarily the self-increment ID value of the inserted data, and therefore does not apply to multithreading.

Second, use the function: msyql_insert_id (); When the system executes the INSERT, and then executes the SELECT, it may have been distributed to a different back-end server, if you use PHP programming, this time should be through mysql_insert_id () To get the latest inserted ID, each time the insert ends, the corresponding AutoIncrement value has been calculated to return to PHP, you do not have to issue a separate query, directly with mysql_insert_id ().

When a statement is inserted, it automatically returns the last ID (MySQL self-increment). And this function is only useful for the current link, that is, it is multi-user-safe. It is recommended to use this function;

Problem: When the ID is bigint, it does not work.

Third, use the query

  1. Msyql_query ("Select last_insert_id ()");
Copy Code

LAST_INSERT_ID () is a MySQL function that also works with the current link this usage resolves the bigint problem encountered in mysql_insert_id ()

Summary: It is recommended to use method two, in special cases, you can consider method three.

  • 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.