What advise, how to find out which number will be assigned to the id field in the database when adding a new id. I add new data from the form to the table, then I need to transfer to another page with the id that the system assigned, is there any solution that allows you to get this information in php?

  • add an entry and then get its id using last_insert_id () or similar functions - Mike

1 answer 1

If you use auto_increment as an identifier, you can get its value using the LAST_INSERT_ID() function and the corresponding query select last_insert_id(); .

  • In this case, you will get the id of the last added record in the table, and not the id of the record you just added. In the general case, these are different records, because during the time of the repeated access to the database, several more transactions could be executed to obtain the LAST_INSERT_ID. In my opinion, if you work in two requests, you must first ask the generator the next ID, and then use it with the INSERT. If in a single query, then do INSERT using a stored procedure on the database side that encapsulates the same logic. Saving unnecessary network access and logic in place. - iTollu
  • In the comment, the limit on the number of characters, so everything did not fit. To test the stated hypothesis, it suffices to conduct load testing with hundreds of simultaneous requests. - iTollu
  • one
    @iTollu I think you should be able in your code to know if other simultaneous requests are being executed in your current connection . Obviously, if the insret operations for the current connection are performed asynchronously, or entail invoking triggers or something else that may affect the return value, then this method is not suitable. But if you have a synchronous code, and immediately after the insert request, you retrieve the resulting ID, then there should be no problem. Several other transactions performed by other users will not affect the result, because it refers to the connection. - teran
  • but since Since php in one-threaded, it is not entirely clear to me what other transactions can occur between two consecutive requests to insert and receive id - teran
  • It agree, in the MySQL documentation found: The ID that was generated is maintained on the per-connection basis. AUTO_INCREMENT value generated by the most recent statement affecting the AUTO_INCREMENT This value can not be affected by other clients, even if they generate AUTO_INCREMENT values ​​of their own. It ensures that it will ensure that it is not a problem. - iTollu