Speeding Up Image Loading from DB

I’m loading 9 images from a database and my syntax looks roughly like this:

<img src="image_loader.php?id=4"></img>

My PHP for image_loader.php looks like:

Read More
<?php
    /* I set up my connection using mysql_connect and mysql_select_db */

    $query = sprintf("SELECT ... FROM ... WHERE id='".$_GET["id"]."'");
    $result = mysql_query($query, $con);
    mysql_close($con);

    if (!$result) {
        // no result
    }
    else {
        $row = mysql_fetch_row($result); 
        header('Content-type: image/png');
        echo $row[0];
        mysql_free_result($result);
        }
?>

Each image is about 10-13k but the bunch seems to be loading very slow. I realize that there is some bottle-necking in the number of requests a browser can execute at a time but the wait times seem to be gratuitous.

Any suggestions on how to get images loaded from a database fast?

Also, and this is almost a separate question, but is it possible to instruct a browser (or server) to cache images with now .gif/.png/.jpg srcs? It seems that Firefox does and Chrome doesn’t, but I’m not certain of this.

enter image description here

Related posts

Leave a Reply

1 comment

  1. I’d first consider whether storing images in a database makes the most sense. It may, but it should be seriously considered, as giving each image a unique filename in the filesystem and storing that in the database will often be faster.

    You would gain additional speed if you could request that file directly from the client as opposed to requesting a generic PHP script that does some sort of fopen()-style abstraction.

    In order to narrow down the source of delay, it first might be helpful to check whether your database is hosted on the same server as your webserver. One indication that it is not hosted locally but on a remote database server is to check the host string you’re providing in the mysql_connect() call. localhost would suggest its local, something else would suggest it’s not. As a note, many shared hosted services (e.g. GoDaddy) split their database server from the webserver.

    For a better idea of the source of the delay, I’d suggest instrumenting your image_loader.php code with timestamps to locate the delay? My guess is that it’ll be in the query.

    If the delay is in your query, you will want to limit the number of queries you make. A strategy that allows you to make one query instead of 9 would limit the impact any webserver-to-database server delay.