What are some best practices for efficiently handling and displaying dynamic content, such as updating images, on a webpage using PHP?

When handling dynamic content like updating images on a webpage using PHP, it's important to ensure efficient loading and display. One way to achieve this is by storing image paths in a database and dynamically retrieving and displaying them on the webpage. This allows for easy updates and changes without having to manually edit the HTML code.

// Connect to database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

$conn = new mysqli($servername, $username, $password, $dbname);

// Retrieve image path from database
$sql = "SELECT image_path FROM images WHERE id = 1";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $image_path = $row["image_path"];
    }
}

// Display image on webpage
echo "<img src='$image_path' alt='Dynamic Image'>";