(mysql, php) How to get auto_increment field value before inserting data?

前端 未结 8 782
挽巷
挽巷 2020-11-29 11:10

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).

8条回答
  •  清歌不尽
    2020-11-29 12:05

    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 :

    • 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
    

提交回复
热议问题