How do I delete the last record inserted into a MySQL table using PDO?

4.4k Views Asked by At

How do I use PDO to delete the last row inserted (this was done in another class)?

I have this, but I don't know what else I'm supposed to do with it:

$pdo = new PDO("mysql:host=$db_host;dbname=$db_name;", $db_user, $db_password);
$stmt = $pdo->prepare('DELETE FROM Resources');
$stmt->execute();
1

There are 1 best solutions below

3
On

After inserting a new record, you get the ID like this:

$insert = $pdo->prepare("INSERT INTO Resources (data) VALUES (:data)");
$insert->execute(array(':data' => $data));
$lastid = $pdo->lastInsertID();

// delete last entry
$delete = $pdo->prepare("DELETE FROM Resources WHERE id = :id LIMIT 1");
$delete->execute(array(':id' => $lastid));