What is the best way to retrieve the last entry from a database in PHP?

To retrieve the last entry from a database in PHP, you can use an SQL query with the ORDER BY clause to sort the entries in descending order based on a timestamp or an auto-incrementing ID column, and then fetch only the first row using LIMIT 1.

// 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);
}

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

if ($result->num_rows > 0) {
    // Output data of the last entry
    $row = $result->fetch_assoc();
    print_r($row);
} else {
    echo "0 results";
}

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