(mysql, php) 如何在插入数据之前获取 auto_increment 字段值? [英] (mysql, php) How to get auto_increment field value before inserting data?

查看:32
本文介绍了(mysql, php) 如何在插入数据之前获取 auto_increment 字段值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将图像文件上传到存储服务器.在上传之前,我应该编写文件名,其中包含 AUTOINCREMENT VALUE(例如,12345_filename.jpg).

I'm uploading image file to storage server. Before uploading I should compose filename, which contains AUTOINCREMENT VALUE in it (for example, 12345_filename.jpg).

如何在插入数据库之前获取自动增量值?

How could I get autoincrement value before inserting into DB?

我只看到一个解决方案

  1. 插入空行
  2. 获取它的自增值
  3. 删除这一行
  4. 使用 p.1 中的自动增量值插入包含真实数据的行

还有其他解决方案吗?

谢谢

推荐答案

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

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)


作为伪代码:

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

这篇关于(mysql, php) 如何在插入数据之前获取 auto_increment 字段值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆