简体   繁体   中英

Get next MySQL row ID when any number of previous rows have been deleted

I have the following call to my database to retrieve the last row ID from an AUTO_INCREMENT column, which I use to find the next row ID:

$result = $mysqli->query("SELECT articleid FROM article WHERE articleid=(SELECT MAX(articleid) FROM article)");
$row = $result->fetch_assoc();
$last_article_id = $row["articleid"];
$last_article_id = $last_article_id + 1;
$result->close();

I then use $last_article_id as part of a filename system.

This is working perfectly....until I delete a row meaning the call retrieves an ID further down the order than the one I want.

A example would be:

ID
0 
1 
2
3
4-(deleted row)
5-(deleted row)
6-(next ID to be used for INSERT call)

I'd like the filename to be something like 6-0.jpg , however the filename ends up being 4-0.jpg as it targets ID 3 + 1 etc...etc...

Any thoughts on how I get the next MySQL row ID when any number of previous rows have been deleted??

You are making a significant error by trying to predict the next auto-increment value. You do not have a choice, if you want your system to scale... you have to either insert the row first, or rename the file later.

This is a classic oversight I see developers make -- you are coding this as if there would only ever be a single user on your site. It is extremely likely that at some point two articles will be created at almost the same time. Both queries will "predict" the same id, both will use the same filename, and one of the files will disappear, one of the table entries may point to the wrong file, and the other entry will reference a file that does not exist. And you'll be scratching your head asking "how did this happen?!"

Predicting auto-increment values is bad practice. Don't do it. Plan for concurrency.

Also, the information_schema tables are not really tables... they are server internals exposed to the SQL interface. Calls to the "tables" table, and show table status are expensive calls that you do not want to make in production... so don't be tempted to use something you find there.

You can use mysql_insert_id() after you insert the new row to retrieve the new key:

$mysqli->query($yourQueryHere); 
$newId = $mysqli->insert_id();

That requires the id field to be a primary key, though (I believe).

As for the filename, you could store it in a variable, then do the query, then change the name and then write the file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM