如何防止弄错ID
database= mysql language=php
我正在编写像这样工作的程序
PC1 =computer1
第 1步
。PC1 插入数据,自动递增的新 ID。
2.PC1 选择最后一个 ID
一切正常,但是..
当您的代码被许多计算机在同一毫秒内使用时出现问题。 例如
- PC1插入数据,自增新ID
2.PC2插入数据,自增新ID
3.PC1选择最后一个ID <--------错误
4PC2选择最后一个ID
如何配置数据库或修改php代码防止这种情况发生,谢谢。
database= mysql language=php
I am coding program to work like this
PC1 =computer1
step
1.PC1 insert data ,new ID from Auto-increment.
2.PC1 select last ID
everything work fine but..
The problem when your code is used by many computers at the same mili-sec.
For example
- PC1insert data,Auto-increment new ID
2.PC2 insert data ,Auto-increment new ID
3.PC1 select last ID <-------Wrong
4PC2 select last ID
How to config database or modify php code to prevent this , thankyou.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您应该使用 mysql_insert_id (或 API 的等效调用您正在使用)来获取最后插入的行的 ID。
我想现在你正在这样做:
除非你使用事务,否则这将不起作用。但使用函数
mysql_insert_id
是更好的方法。在文档中还有一个警告和一些您应该阅读的注释:
You should use mysql_insert_id (or the equivalent call for the API you are using) to get the ID of the last inserted row.
I imagine that now you are doing this:
This won't work unless you use transactions. But using the function
mysql_insert_id
is the better way.In the documenation there is also a caution and some notes that you should read:
在 mysql 中,如果调用
SELECT LAST_INSERT_ID();
您将获得当前连接的最后一个自动生成的 ID,而不是整个服务器。因此,如果在另一个连接中创建另一条记录,则不会影响 LAST_INSERT_ID() 返回的结果。
in mysql if you call
SELECT LAST_INSERT_ID();
you will get the last auto generated id fro the current connection, not for the whole server. So if another record is created in another connection it wont effect the result returned by LAST_INSERT_ID().
MySQL 将在每个客户端(计算机)连接的任何
INSERT
语句之后立即返回正确的最后插入的 ID,因此您不必担心这一点;服务器不会混淆它们。来自文档:只要您在 PHP 代码中调用 mysql_insert_id() 来检索插入 ID,就无需担心。
MySQL will return the correct last-inserted ID right after any
INSERT
statement per client (computer) connection, so you won't have to worry about that; the server won't mix them up. From the documentation:As long as you call
mysql_insert_id()
in your PHP code to retrieve the insert ID, there's nothing to worry about.mySQL 具有
LAST_INSERT_ID()
功能。PHP 等效项(如果您使用经典的 mysql 函数)是 < code>mysql_insert_id(),但该函数应在 INSERT 查询之后立即调用,因为它作用于最后执行的查询。
这些功能在每个连接的基础上工作,不会受到其他客户端插入的记录的影响。
mySQL has the
LAST_INSERT_ID()
function for that.The PHP equivalent (if you use the classical mysql functions) is
mysql_insert_id()
with the exception that this function should be called immediately after the INSERT query because it acts on the last query made.These functions work on a per-connection basis, it will not be influenced by records inserted by other clients.