Optimised Images Taking A Long Time To Load When Fetched From MySQL Database (via PHP)

  mysql, php

I have some responsive images that are being outputted onto a page where the URLs come from filenames stored in a MySQL database. The images, although optimised (even the large versions are < 200KB), always take 5.00s to load.

The code is below, at this stage there are only 6 images in the database for testing, but I can’t work out why this kills the page-load speed. When I remove the images or add in a static image taken from a site folder and type the path manually this issue doesn’t happen.

The $filename is a taken from a URL parameter on the page and the details then fetched from the MySQL database with PHP.

The images are produced at 3 different sizes when uploaded with the Imagick PHP library (500,750 and 1000px) and the sizes added via string concatenation.

The problem may be being caused by the MySQL database itself on MAMP, but as well as looking into that I thought I’d better check I’m not doing something completely wrong here (I’m relatively new to PHP/MySQL and web development generally).


isset($_GET['filename']) ? $filename = $_GET['filename'] : header("Location: login.php");

$stmt = $connection->prepare("SELECT * FROM imageposts WHERE filename = :filename");

':filename' => $filename

$www_root = "http://localhost:8888/site";

$db_image_filename = htmlspecialchars($row['filename']);
$db_image_ext = htmlspecialchars($row['file_extension']);
$db_image_title = htmlspecialchars($row['image_title']);


// image output

src="<?php echo $www_root . '/images-lib/' . $db_image_filename . '-500' . '.' . $db_ext; ?>"
srcset="<?php echo $www_root . '/images-lib/' . $db_image_filename . '-500' . '.' . $db_ext; ?> 500w,
        <?php echo $www_root . '/images-lib/' . $db_image_filename . '-750' . '.' . $db_ext; ?> 750w"
alt="<?php echo $db_image_title; ?>" 
title="<?php echo $db_image_title; ?>"

Note: a typical filename is 614b66956a121_1632331413-500 which is generated via the Imagick library when the image is uploaded, and $db_ext is either .jpeg or .png

Source: Ask PHP