How can developers improve code readability and maintainability when working with PHP and MySQL for image display?
Issue: Developers can improve code readability and maintainability when working with PHP and MySQL for image display by separating concerns, using proper naming conventions, and implementing reusable functions for database queries and image handling.
// Example of separating concerns, using naming conventions, and reusable functions
// Database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
$conn = new mysqli($servername, $username, $password, $dbname);
// Function to get image data from database
function getImageData($conn, $imageId) {
$sql = "SELECT * FROM images WHERE id = $imageId";
$result = $conn->query($sql);
return $result->fetch_assoc();
}
// Function to display image
function displayImage($imageData) {
echo '<img src="' . $imageData['image_path'] . '" alt="' . $imageData['image_alt'] . '">';
}
// Get image data from database
$imageId = 1;
$imageData = getImageData($conn, $imageId);
// Display image
displayImage($imageData);
// Close database connection
$conn->close();