Portal Home > Knowledgebase > Articles Database > Finding out the highest number in an auto-incrementing table
Finding out the highest number in an auto-incrementing table
Posted by FinalFrontier, 01-21-2012, 06:24 AM |
I have a row in a MySQL table called id, which auto-increments.
I was wondering if anyone knows a PHP solution to find out what the highest number in the row is?
I am thinking perhaps execute a MySQL query that will list the highest number, and then echo the result - like $row[id]) in PHP?
Last edited by FinalFrontier; 01-21-2012 at 06:28 AM.
|
Posted by Steve_Arm, 01-21-2012, 06:28 AM |
SELECT id FROM table ORDER BY id DESC LIMIT 1
|
Posted by josephgarbett, 01-21-2012, 06:39 AM |
|
Posted by MrKenTX, 01-24-2012, 01:53 AM |
MySql has a MAX function.
|
Posted by foobic, 01-24-2012, 10:57 AM |
Why do you want to know the highest id in the table? If the answer is what I'm guessing it is, you probably want mysql_insert_id.
|
Posted by topgun, 01-24-2012, 04:39 PM |
FYI, the highest row id is not necessarily the same as the auto increment count. What if you delete the last row for example?
|
Posted by foobic, 01-24-2012, 09:10 PM |
Yes, or if you have another thread inserting a new record then again, they can give different answers. But which answer is "right"?
That's why I asked what the OP wants with the information. If (as is very often the case) he wants to insert a new record and then find out what its auto-generated id is, say to update some other table, then using MAX(id) is wrong and creates the worst kind of bug - one that produces correct answers most of the time, but not always...
|
Posted by hodgeemory, 01-28-2012, 03:13 AM |
You may want to use AUTO INCREMENT to have MySQL automatically ... Inserts a row into the table using the data defined in the VALUES section
|
Posted by topgun, 01-28-2012, 05:38 AM |
This is the only correct answer.
The OP is already using auto increment.
|
Posted by 8088, 01-28-2012, 08:07 PM |
If the OP wants to know the id that matches his last inserted record, like foobic already suspected, you'll end up with a race condition if you use this answer.
|
Add to Favourites Print this Article
Also Read