How can SQL queries be optimized to display the last 3 update messages in PHP?

To optimize SQL queries to display the last 3 update messages in PHP, you can use the ORDER BY clause in your SQL query to sort the messages by the update timestamp in descending order, and then limit the result set to only return the last 3 messages. This way, you can efficiently retrieve and display the most recent update messages without fetching unnecessary data.

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

// SQL query to retrieve the last 3 update messages
$sql = "SELECT message FROM updates_table ORDER BY timestamp DESC LIMIT 3";
$result = $conn->query($sql);

// Display the last 3 update messages
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo $row["message"] . "<br>";
    }
} else {
    echo "No update messages found.";
}

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