Summary of several methods for php to obtain id with newly inserted data

  • 2021-10-13 06:51:21
  • OfStack

When inserting data into mysql, many times we want to know the id that just inserted data, which is very useful to us. Here are three commonly used methods and 11 analyze their advantages and disadvantages.

1 Use the following statement:


mysql_query("select max(id) from t1",$link);

When we use this method, we get the maximum value of id, but the maximum value of id is not 1 when we multi-link threads, so this does not use domain threads.

2 Use the following function:


msyql_insert_id();

When the system executes INSERT, When SELECT is executed again, It may have been distributed to different back-end servers, If your programming language is PHP, The latest id insertion should be obtained by mysql_insert_id (), After each INSERT, In fact, the corresponding autoincrement value has been calculated and returned to PHP, you don't need to issue an independent query, and you can use mysql_insert_id () directly. This function is very easy to use. When we insert a statement, it automatically returns the last id value and this function is only useful for the current link, that is to say, it is multi-user secure, so we often use this function;

But this function has a problem is when id for bigint type will not work, so now using this function please be careful, but we rarely encounter such a problem, so you can not care about it.

3: Query with 1


msyql_query("select last_insert_id()");

last_insert_id () is an mysql 1 function that also works on the current link. This usage solves the bigint type problem encountered in mysql_insert_id ().

Summary: According to the above analysis, the first method should be used as little as possible and the second method should be used as much as possible. When encountering special circumstances, the third method can be considered


Related articles: