note 81129 deleted from function.mysql-insert-id by googleguy
| From: | googleguy@php.net | Date: | Wed, 19 Jun 2013 22:28:11 +0000 |
| Subject: | note 81129 deleted from function.mysql-insert-id by googleguy | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-195293@lists.php.net to get a copy of this message | ||
Note Submitter: venimus at gmail dot com
----
To get the most accurate NEXT auto_increment id use this function
<?php
function mysql_next_id($table) {
$result = mysql_query('SHOW TABLE STATUS LIKE "'.$table.'"');
$rows = mysql_fetch_assoc($result);
return $rows['auto_increment'];
}
?>
Any other methods of predicting the next autogenerated id will fail in certain cases.
Most of the programmers try to get the MAX(id)+1 (or sort the table backwards and get the first id)
but this will cease to work when you delete the last record.
However in a race condition even this function may fail if other users insert records in the time
between calling this function and using the return value. You may use LOCK TABLES to prevent such a
case.
Anyway, the best advice I can give you is to RECONSIDER YOUR LOGIC TO AVOID USING AUTO_INCREMENT.