What are the best practices for efficiently retrieving the ID of the last entry in a MySQL table when working with PHP?

When working with MySQL and PHP, efficiently retrieving the ID of the last entry in a table can be achieved by using the `ORDER BY` and `LIMIT` clauses in a SQL query. By sorting the entries in descending order based on the ID column and limiting the result to 1, you can retrieve the last entry's ID effectively. This approach ensures that only the necessary data is fetched from the database, improving performance.

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

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

// Query to retrieve the ID of the last entry in the table
$query = "SELECT id FROM table_name ORDER BY id DESC LIMIT 1";
$result = $mysqli->query($query);

// Check if query was successful
if ($result) {
    $row = $result->fetch_assoc();
    $last_entry_id = $row['id'];
    echo "The ID of the last entry is: " . $last_entry_id;
} else {
    echo "Error: " . $mysqli->error;
}

// Close connection
$mysqli->close();