问题
I have an mysql table with an column called "id" - this column has auto increment set.
I only want to know how i can get, with PHP and PDO, the next auto increment value, without doing a INSERT INTO query. (i found some questions about this - but none without INSERT INTO and only based on mysqli).
Thanks!
回答1:
Why do you need this ?
If you need, you can get the current auto increment value like this, but I don't see a situation where this would be needed.
SELECT `AUTO_INCREMENT`
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'DatabaseName'
AND TABLE_NAME = 'TableName';
More info:
- Get current AUTO_INCREMENT value for any table
回答2:
The very statement of the question is wrong.
You actually don't need it, as without the INSERT query this value makes absolutely no sense.
Although I do understand that simplicity of PHP language welcomes anyone into the world of web-programming, it still requires some knowledge. One of the things you have to understand is the purpose and the meaning of the autoincremented unique identifier. Which is not what you think. It makes sense ONLY after insert and nowhere else.
So, there could be only two possible scenarios:
- either you really need a freshly generated id - then just insert a record, get that id and use it
- or you are confusing this value with something else and thus don't need it at all
回答3:
I can see reasons why you would want / need this. We use it as part of security for new clients which keeps the 'keys' unique without having to send additional queries to the DB.
$q = $db->query("SHOW TABLE STATUS LIKE 'yourtable'");
$next = $q->fetch(PDO::FETCH_ASSOC);
echo $next['Auto_increment'];
回答4:
One line solution :
$var = $db->query("SHOW TABLE STATUS LIKE 'my_table'")->fetch(PDO::FETCH_ASSOC)['Auto_increment'];
回答5:
be careful because between you ask the next ID and when you want to use it, someone concurent query can insert a new record and the ID you get is no longer valid
let's say when you want to add new person record when you didn't know the name, want to put newPerson
get the id write to db newPerson
but this could happend:
get1 the id get2 the id write1 to db newPerson write2 to db newPerson
where 1 and 2 are two concurent scripts that happens to execute at the same time
easy fix would be to use transactions, to avoid this
来源:https://stackoverflow.com/questions/18508521/get-next-auto-increment-from-mysql-table-with-pdo-without-insert