Reputation: 3618
I'm basically trying to make a "goal" bar. The goal is determined by getting the last entry I made in a MySQL table. I want to get the ID of the last entry therefore.
How do I get the last entry in the table and then get the id from that last entry?
(Using PHP)
Upvotes: 23
Views: 84355
Reputation: 3765
The above answers show how to get the latest entry by id. If one uses non-incrementing ids such as UUIDs as keys, this does not work. In that case one could use a created_at
column instead.
-- highest id
SELECT * FROM some_table ORDER BY id DESC LIMIT 1;
-- latest created at date
SELECT * FROM some_table ORDER BY created_at DESC LIMIT 1;
Upvotes: 0
Reputation: 8461
if the field is auto-incremented then you can use LAST_INSERT_ID
Upvotes: 2
Reputation: 241
Get the latest entry of a user
'SELECT user_id FROM table_name WHERE user_id = '.$userid.' ORDER BY user_id DESC LIMIT 1';
Upvotes: 2
Reputation: 27
select all fields from table in reverse order and set limit 0,1 This will give you last result of table field data
Upvotes: 2
Reputation: 1151
you can use LAST_INSERT_ID()
function. example:
$sql = "SELECT * FROM mytable WHERE id = LAST_INSERT_ID()";
Upvotes: 8
Reputation: 27474
To do this reliably, you must have some field in the table that you can examine to determine which is last. This could be a time stamp of when you added the record, a sequence number that continually increases (especially an auto-incrementing sequence number), etc.
Then, let's suppose it's a sequence number called "rec_seq". You'd write something like:
select * from my_table
where rec_seq=(select max(rec_seq) from my_table)
Upvotes: 3
Reputation: 3695
you can use this query to get the results you want with this sql query as used in this example:
$sql = "SELECT user_id FROM my_users_table ORDER BY user_id DESC LIMIT 0,1";
Upvotes: 6
Reputation: 60498
To get the greatest id:
SELECT MAX(id) FROM mytable
Then to get the row:
SELECT * FROM mytable WHERE id = ???
Or, you could do it all in one query:
SELECT * FROM mytable ORDER BY id DESC LIMIT 1
Upvotes: 59