I considered the top google results, almost all functions of mysql and etc... Unfortunately, as far as I learned, without adding a new row into the table of a database, we can't know the next primary key. Please, say me I'm wrong. How can't there be any solution for this problem? I am disappointed.
Asked
Active
Viewed 976 times
2
-
You can't for certain (even reading the next value to be assigned by MySQL isn't guaranteed if you have multiple concurrent users); but the real question is "why should you need to?" – Mark Baker Jul 28 '15 at 15:42
-
Because, in my project, I'm uploading pictures with AJAX, and beside it, then the article which contains the images is submitted . So I need to put a foreign key for the pictures so that they can related to candidate article. That is, I need to learn the primary key of the candidate article to be able to put this value as foreign key for images in the article. – Hasan Jul 28 '15 at 15:45
-
Still doesn't require predicting the next id that will be assigned – Mark Baker Jul 28 '15 at 15:52
3 Answers
2
Took about 7 seconds to find on Google: https://www.bram.us/2008/07/30/mysql-get-next-auto_increment-value-fromfor-table/
SELECT AUTO_INCREMENT
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = "databaseName"
AND TABLE_NAME = "tableName"

Siyual
- 16,415
- 8
- 44
- 58
2
The value is present in INFORMATION_SCHEMA.TABLES
(see here). Under reasonable assumptions, you can get the value there.
Reasonable assumptions:
- No changes to the system variables that affect auto increment.
- No concurrent transactions.
- No intervening reset of the value.

Gordon Linoff
- 1,242,037
- 58
- 646
- 786
0
with this request you have the last id in your table
SELECT MAX(id) FROM your_table
You can just add +1 to your request result.

snippster
- 98
- 10