tags:

views:

39

answers:

3

I want to delete the most recent entry in MySQL using PHP, is there a function that allows me to do that?

$query2 = "DELETE FROM test WHERE ___";

+6  A: 

Assuming you have an AUTO_INCREMENT field on your table, you can do this:

DELETE FROM test WHERE test_id = LAST_INSERT_ID()

Matt
perfect! Thank you!
ggfan
This query fails if a second client/connection add a *newer* row with a higher ID or if the `LAST_INSERT_ID()` from the last INSERT INTO command wasn't for the table `test` but for a different table.
Progman
+1  A: 

You need a datetime column which saved the current time during the INSERT INTO query. Then you can use the ORDER BY and LIMIT keywords to delete the last entry in your table.

DELETE FROM
    tab
ORDER BY
    datecolumn DESC
LIMIT 1

Check the MySQL 5.1 Reference Manual - 12.2.2 DELETE Syntax for the following statement:

If the DELETE statement includes an ORDER BY clause, rows are deleted in the order specified by the clause. This is useful primarily in conjunction with LIMIT.

Progman
+1  A: 
DELETE FROM table WHERE id = MAX(id) LIMIT 1

should also be working if you are using auto increment

knittl
If my table name is "test" and the auto increment id is counter_id.$query2 = "DELETE FROM test WHERE counter_id = MAX(counter_id) LIMIT 1";That query doesn't seem to be deleting from the table.
ggfan
strange, it should be
knittl
maybe the `LIMIT 1` is giving problems, because it will not find the total maximum, but only the local maximum in your limited records (so max with limit 1 will only show the first row)
knittl