Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...

When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

Storing Images In MySQL

Note: This article has been replaced by Storing Images in MySQL Revisited (by Quentin Zervaas, 2010). We've left this article here for historical purposes, but we strongly recommend you use the newer article instead.

Displaying The Image

Now we have the ability to get the images into the database, we need to be able to get it out.

Here we see a simple script to display an image based on its image_id in the database. Of course you should do more checking on the value of $_GET['image_id'] here. We will call this file view.php.

Listing 6 file.php
    // just so we know it is broken
    // some basic sanity checks
    if(isset($_GET['image_id']) && is_numeric($_GET['image_id'])) {
        //connect to the db
        $link = mysql_connect("localhost", "username", "password") or die("Could not connect: " . mysql_error());
        // select our database
        mysql_select_db("testblob") or die(mysql_error());
        // get the image from the db
        $sql = "SELECT image FROM testblob WHERE image_id=0";
        // the result of the query
        $result = mysql_query("$sql") or die("Invalid query: " . mysql_error());
        // set the header for the image
        header("Content-type: image/jpeg");
        echo mysql_result($result, 0);
        // close the db link
    else {
        echo 'Please use a real id number';

In This Article

Article History

Apr 18, 9804
Initial article version
Jan 18, 2008
Updated listing 5 to not include non-existent conf.php