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

前端 未结 8 713
挽巷
挽巷 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
    
    0 讨论(0)
  • 2020-11-29 12:16

    Well this is to old ,but if someone else need it.

    You can get this kind of value at "information_schema" table where you could do something like

    select AUTO_INCREMENT from TABLES where TABLE_SCHEMA = 'You're Database' and TABLE_NAME = 'Table Name'
    

    So this kind of Meta Data are always stored in Information_schema .

    0 讨论(0)
提交回复
热议问题