What are the best practices for delivering images through a PHP script from a database?

When delivering images through a PHP script from a database, it is best practice to store the image data in the database as a BLOB (Binary Large Object) and then retrieve and output the image using a PHP script. To optimize performance, it is recommended to use caching techniques to reduce database queries and improve loading times.

<?php
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
$conn = new mysqli($servername, $username, $password, $dbname);

// Retrieve image data from the database
$sql = "SELECT image_data FROM images WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $id);
$id = 1; // Example image ID
$stmt->execute();
$stmt->bind_result($imageData);
$stmt->fetch();
$stmt->close();

// Output the image
header("Content-type: image/jpeg"); // Change content type based on image type
echo $imageData;

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