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

查看:257
本文介绍了(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. 使用第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)


作为伪代码:


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

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

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