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

前端 未结 8 712
挽巷
挽巷 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 11:49

    There is no solution. You get the auto-increment value when you insert a new row, full stop. Inserting and deleting won't help, since the next auto-increment value will be one higher. Do to possibly multiple clients talking to the database at the same time, you can't predict the next value since it might be incremented between your guessing and your actual insert.

    Find a different solution. Either insert a row and update it later, or generate an id for the filename that's independent of the auto-increment id.

    0 讨论(0)
  • 2020-11-29 11:51

    Use a separate table just as a counter, like a postgresql sequence, and don't use auto_increment in your main table(s).

    0 讨论(0)
  • 2020-11-29 11:52

    well, try this:

    $query = "SHOW TABLE STATUS LIKE 'tablename'";
    $result = mysql_query($query);
    $row = mysql_fetch_assoc($result);
    var_dump($row);
    

    output:

    array(18) {
    [...]
    ["Auto_increment"]=> string(4) "3847"
    [...]
    }
    

    This will be your next auto_increment ID.

    0 讨论(0)
  • 2020-11-29 11:57

    INSERT INTO CONTACTS1 (firstname, lastname) values('hi', select auto_increment from information_schema.TABLES where TABLE_NAME='CONTACTS1' and TABLE_SCHEMA='test')

    Where ID is the Primary Key & Auto number column.

    0 讨论(0)
  • 2020-11-29 11:59

    @Pascal Martin makes a good point. In cases like this, I personally like to add another ID column, containing a random, 16-digit ID (which will also be the "public" ID in web apps and on web sites for security reasons). This random ID you can set beforehand in your application, work with it, and then set when the record is actually created.

    0 讨论(0)
  • 2020-11-29 12:00

    If you are using PDO, here is a "single line" solution :

    $nextId = $db->query("SHOW TABLE STATUS LIKE 'tablename'")->fetch(PDO::FETCH_ASSOC)['Auto_increment'];
    

    where tablename is replaced by your table.

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