Reputation: 12662
I am trying to select the last record from a table in MySQL using PHP. I believe I have an SQL error. Here is my SQL code:
SELECT TOP 1 id FROM `table` ORDER BY id DESC
If this is valid and I actually have a PHP error, tell me.
Upvotes: 28
Views: 82834
Reputation: 19
This will work To find the last record if you are not looking to use limit
SELECT TOP 1 * FROM Products ORDER BY id desc
This will work To find the last record specifying column name if you are not looking to use limit
SELECT TOP 1 id FROM Products ORDER BY id desc
Else
SELECT * FROM Products ORDER BY id DESC LIMIT 1
Upvotes: 0
Reputation: 23125
A simpler and more DBMS-agnostic approach would be:
SELECT MAX(id) AS id
FROM table
That's only if you want just the id
field, otherwise if you tried to SELECT other columns, it wouldn't return matching data to the id
field and you would instead have to use:
SELECT id, otherfields, ..., ...
FROM table
WHERE id = (SELECT MAX(id) FROM table)
Upvotes: 12