PHP Gets the ID of the last inserted data

Source: Internet
Author: User

many times we want to know when inserting data to MySQL
The ID of the channel just inserted the data this is useful for us. Below I say three kinds of common
methods and analyze their pros and cons
one with the following statement:

mysql_query ("SELECT Max (ID) from T1", $link);

When using this method, we get the value that is the maximum ID, but when the last one is a multi-link thread
This maximum ID is not necessarily the one we inserted so this does not take advantage of the domain thread
two uses the following function:

MSYQL_INSERT_ID ();

When the system executes the INSERT, and then select, it may have been distributed to a different back-end server
, if the programming language you are using is PHP, you should get the newly inserted ID by mysql_insert_id () .
after each insert is finished,
in fact, the corresponding AutoIncrement value has been calculated to return to PHP, you do not have to issue a separate query,
Direct use of mysql_insert_id () is possible.
This function is very useful when we insert a statement, it automatically returns the last ID value.
and this function is only useful for the current link, which means it's multi-user safe.
so we often use this function;
But the problem with this function is that it doesn't work when the ID is bigint, so be careful with this function now .
However, we seldom encounter such problems, so we can not take care of it
Three: Use the query

Msyql_query ("Select last_insert_id ()");

last_insert_id () is a MySQL function that is also valid for the current link
This usage resolves the bigint type problem encountered in mysql_insert_id ()


Summary: Based on the above analysis of the first method to minimize the use of the second method when encountering special circumstances can consider the third method

PHP Gets the ID of the last inserted data

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.