且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

(mysql,php)如何在插入数据之前获取auto_increment字段值?

更新时间:2022-12-12 15:03:03

插入完成后,自动增量值由数据库本身生成;这意味着您无法在执行实际的插入查询之前得到它.

The autoincrement value is generated by the database itself, when the insertion is done ; which means you cannot get it before doing the actual insert query.

您提出的解决方案不是经常使用的解决方案-应该是:

The solution you proposed is not the one that's often used -- which would be :

  • 插入一些半空数据
  • 获取已生成的自动增量值
  • 使用该自动增量值进行计算
  • 更新该行以放置新的/完整的数据-使用先前在update查询的where子句中生成的自动增量,以标识要更新的行.
  • insert some half-empty data
  • get the autoincrement value that's been generated
  • do your calculations, using that autoincrement value
  • update the row to put the new / full data in place -- using the autoincrement generated earlier in the where clause of the update query, to identify which row is being updated.

当然,为了安全起见,所有这些操作都必须在事务中进行(以确保全有或全无"行为)

Of course, as a security precaution, all these operations have to be made in a transaction (to ensure a "all or nothing" behavior)


作为伪代码:


As pseudo-code :

begin transaction
insert into your table (half empty values);
$id = get last autoincrement id
do calculations
update set data = full data where id = $id
commit transaction