What is the best approach to output only the last 4 entries from a table with many entries in PHP?

When dealing with a table with many entries and needing to output only the last 4 entries, we can achieve this by querying the database in descending order and limiting the results to 4. This way, we will retrieve the latest entries first and then output only the last 4 entries.

// Connect to 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 last 4 entries
$sql = "SELECT * FROM table_name ORDER BY id DESC LIMIT 4";
$result = $conn->query($sql);

// Output the last 4 entries
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "ID: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
    }
} else {
    echo "0 results";
}

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