How can the last entry in a database table be deleted using a SQL query in PHP?

To delete the last entry in a database table using a SQL query in PHP, you can first retrieve the primary key of the last entry using a SELECT query ordered by the primary key in descending order. Once you have the primary key, you can use a DELETE query to remove the entry from the table.

<?php

// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Get the primary key of the last entry
$sql = "SELECT id FROM table_name ORDER BY id DESC LIMIT 1";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$id = $row['id'];

// Delete the last entry
$sql = "DELETE FROM table_name WHERE id = $id";
if ($conn->query($sql) === TRUE) {
    echo "Last entry deleted successfully";
} else {
    echo "Error deleting record: " . $conn->error;
}

// Close the connection
$conn->close();

?>