This article mainly introduces three methods for PHP to obtain the new MySql Record ID value, which can be achieved by using the built-in function mysql_insert_id () in PHP. The other two methods can be used in special cases, for more information, see
This article mainly introduces three methods for PHP to obtain the new MySql Record ID value, which can be achieved by using the built-in function mysql_insert_id () in PHP. The other two methods can be used in special cases, for more information, see
I. Statement:
The Code is as follows:
Mysql_query ("select max (id) from t1", $ link );
This method is used to obtain the largest value of id, which is indeed the last value. However, when multiple threads are connected, this largest id is not necessarily the auto-incremental id value of the inserted data, therefore, it is not applicable to multithreading.
2. Use the function: msyql_insert_id ();
In PHP, the id value inserted into the database is often taken out, and there is such a function:
The Code is as follows:
<? Php
// Execute the statement for inserting the database
//......
$ GetID = mysql_insert_id (); // $ getID is the ID of the last record
// Conditions for using this function:
// 1. Assume that the field name is recordID
// 2. Set the field attribute to auto_increment.
// 3. Use it after adding data
// $ NewID = mysql_insert_id ();
// Obtain the ID value
?>
The PHP function mysql_insert_id () returns the value of the field defined by AUTO_INCREMENT after the last INSERT query is executed.
When the system executes the INSERT statement and then runs the SELECT statement, it may have been distributed to different backend servers. If php is used for programming, you should use mysql_insert_id () to get the latest inserted id. After each INSERT operation, the corresponding autoincrement value is calculated and returned to PHP. You do not need to issue an independent query and directly use mysql_insert_id () you can.
When a statement is inserted, it automatically returns the last id (mysql auto-increment ).
And this function is only useful for the current link, that is, it is a multi-user security type.
We recommend that you use this function;
Problem: it does not work when the id is bigint.
Iii. Use Query
The Code is as follows:
Msyql_query ("select last_insert_id ()");
Last_insert_id () is a mysql function that also takes effect on the current link.
This method solves the bigint type problem in mysql_insert_id ().
Summary:
Method 2 is recommended. In special cases, you can consider method 3.