如何防止ID错误 [英] how to prevent from getting wrong ID
问题描述
database = mysql language = php
我是编程程序,工作方式如下
PC1 = computer1
步骤
1.PC1从自动递增中插入数据,新ID。
2.PC1选择最后一个ID
一切正常,但...
当你的代码被同一个mili-sec上的许多计算机使用时的问题。
例如
- PC1插入数据,自动递增新ID
2.PC2插入数据,自动增加新ID
3.PC1选择最后一个ID <-------错误
4PC2选择最后一个ID
如何配置数据库或修改PHP代码以防止出现这种情况,谢谢。 / p>
您应该使用 mysql_insert_id (或者您正在使用的API的等效调用)来获取最后插入的行的ID。
我想象现在你正在这样做:
SELECT MAX(id)FROM yourtable
这不会工作,除非你使用交易。但是使用函数 mysql_insert_id
是更好的方法。
文档也有一些警告和一些注释,您应该阅读:
注意:mysql_insert_id将本机MySQL C API函数mysql_insert_id()的返回类型转换为long类型(在PHP中命名为int)。如果AUTO_INCREMENT列的列类型为BIGINT(64位),则转换可能会导致值不正确。
注意:因为mysql_insert_id()会对最后执行的查询执行操作,因此会在SQL查询中使用内部MySQL SQL函数LAST_INSERT_ID ,请务必在生成该值的查询后立即调用mysql_insert_id()。
注意:MySQL SQL函数LAST_INSERT_ID )始终包含最近生成的AUTO_INCREMENT值,并且在查询之间不会重置。
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.
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:
SELECT MAX(id) FROM yourtable
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:
Caution: mysql_insert_id() will convert the return type of the native MySQL C API function mysql_insert_id() to a type of long (named int in PHP). If your AUTO_INCREMENT column has a column type of BIGINT (64 bits) the conversion may result in an incorrect value. Instead, use the internal MySQL SQL function LAST_INSERT_ID() in an SQL query.
Note: Because mysql_insert_id() acts on the last performed query, be sure to call mysql_insert_id() immediately after the query that generates the value.
Note: 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.
这篇关于如何防止ID错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!