I have a table into which new data is frequently inserted. I need to get the very last ID of the table. How can I do this?
Is it similar to SELECT MAX(id) FROM table
?
I have a table into which new data is frequently inserted. I need to get the very last ID of the table. How can I do this?
Is it similar to SELECT MAX(id) FROM table
?
$lastid = mysql_insert_id();
If you're using PDO, use
PDO::lastInsertId
.If you're using Mysqli, use
mysqli::$insert_id
.If you're still using Mysql:
But if you have to, use
mysql_insert_id
.I tried
mysqli_insert_id($dbConnectionObj)
This returns the current connection's last inserted id so if you are managing your connections properly this should work. Worked for me at least.
Please use PDP and then try this
Using
MySQLi
transaction I sometimes wasn't able to getmysqli::$insert_id
, because it returned 0. Especially if I was using stored procedures, that executingINSERT
s. So there is another way within transaction:By all this discussion I assume that the reason to check max id is to know what id should be next.. (if my max id is 5 then next will be 5+1=6).
>>If this is not the reason, my best apologies
Case if someone else INSERTs information between your CHECK and INSERT would give you wrong ID.
So It can be solved if you would create hash that could include timestamp or other unique value.
Then in the same function you can insert your information with empty values and your hash. That would create ID if you have AUTO_INCRECEMENT selected.
Then in the same function you would still have your hash and you could look for id with the same hash. And then you could complete populating empty values with mysql UPDATE.
This includes a bit more connections, but it is still a way to do it...
Good luck solving it.