What happens if mysql_insert_id called form different places and different browsers at the same time?

六月ゝ 毕业季﹏ 提交于 2019-12-24 10:22:40

问题


Maybe i have some stupid questions about mysql_insert_id...

I need to get the last inserted Id of a query using mysql_insert_id after mysql_query("INSERT INTO").

mysql_insert_id retrieves the generated Id by the previous query, but my question is...

One php file called test.php with the following code

mysql_query("INSERT INTO table (FirstName, LastName) VALUES ('" . $_POST['FirstName'] . "', '" . $_POST['LastName'] . "'); ")
$lastId = mysql_insert_id();
...continues some code using $lastId

What happens if the test.php file called from different places and different browsers at the SAME TIME ? or what happens if other php file that containts INSERT INTO query called at the same time ?

What actually Id gets back the mysql_insert_id() ? We have to do with a rare probability ?

I do not know if I become understandable...


回答1:


The PHP manual states that the value of mysql_insert_id() returns only the most recently generated AUTO_INCREMENT value:

The value of the MySQL SQL function LAST_INSERT_ID() always contains the most recently generated AUTO_INCREMENT value, and is not reset between queries.

The MySQL manual states the it will return the last AUTO_INCREMENT based on a per-connection basis:

The ID that was generated is maintained in the server on a per-connection basis. This means that the value returned by the function to a given client is the first AUTO_INCREMENT value generated for most recent statement affecting an AUTO_INCREMENT column by that client. This value cannot be affected by other clients, even if they generate AUTO_INCREMENT values of their own. This behavior ensures that each client can retrieve its own ID without concern for the activity of other clients, and without the need for locks or transactions.

Additionally, you should stop using mysql_ functions as they are being deprecated.




回答2:


Each client will be sitting on a separate connection. mysql_insert_id() will get the id of the last insert query, based on the passed/current connection. So you don't have to worry about multiple scripts causing problems.

Also, from the code you provided above, your script is vulnerable to a SQL injection attack. Escape your user-input or even better, use PDO/MySQLi.




回答3:


You get back the autoincrement ID from the last query on your connection. It will not cross connections, so there is no harm in two scripts running simultaneously.

Side note: if you have the option, use the mysqli or PDO libraries instead of the deprecated mysql libarary.



来源:https://stackoverflow.com/questions/12467111/what-happens-if-mysql-insert-id-called-form-different-places-and-different-brows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!