What is the best practice for deleting the last entry in a database table using PHP?

When deleting the last entry in a database table using PHP, it is important to first determine the primary key of the last entry, then use a DELETE query to remove that specific row 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 in the table
$sql = "SELECT MAX(id) AS max_id FROM table_name";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$last_id = $row['max_id'];

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

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