Skip to content
PHP Logo

What is the best way to display the latest record in a database with a timestamp field using PHP?

To display the latest record in a database with a timestamp field using PHP, you can query the database to retrieve the record with the highest timestamp value. You can achieve this by sorting the results in descending order based on the timestamp field and limiting the query to return only one record.

php
<?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);
}

// Query to retrieve the latest record based on timestamp field
$sql = "SELECT * FROM your_table_name ORDER BY timestamp_field DESC LIMIT 1";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // Output data of the latest record
    $row = $result->fetch_assoc();
    echo "Latest Record: " . $row["column_name"];
} else {
    echo "0 results";
}

$conn->close();
?>