(mysql, php) How to get auto_increment field value before inserting data?
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?
I see only one solution
- insert empty row
- get it's autoincrement value
- delete this row
- insert row with real data using autoincrement value from p.1
Is there any other solutions?
Thank you
Solution 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 :
- 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 theupdate
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
Solution 2:
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.
Solution 3:
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.
Solution 4:
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.