How can I retrieve the last record from a database using PHP?

To retrieve the last record from a database using PHP, you can use an SQL query with the ORDER BY clause to sort the records in descending order based on a unique identifier (such as an auto-incremented ID) and then limit the result to 1. This will fetch the last record in the database.

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

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

// Retrieve the last record from the database
$query = "SELECT * FROM table_name ORDER BY id DESC LIMIT 1";
$result = $connection->query($query);

// Fetch the last record
if ($result->num_rows > 0) {
    $row = $result->fetch_assoc();
    // Process the last record here
} else {
    echo "No records found";
}

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