March 18, 2012

Retrieving Image from MySQL with PHP

Question by Dev Newb

I understand the debate over whether to store images in the database but I’m stuck with this design for now. I also know that this topic has been covered a thousand times in terms of pulling the MySQL BLOB into a separate php file for display purposes. My question is a little more narrow and I haven’t seen it anywhere.

I am looping image results from my database into an HTML table that shows the file description and upload date. All I want is the file description hyperlinked so when my users click on it the actual image is displayed. I have this working fine in another script where they choose the image from a dropdown and it POSTS the information to another script. For some reason I am wrapped around the axle on how to display the image from a simple hyperlink. I am trying to do this but it displays all the BLOB data on the page. Can someone point me in the right direction on this one?

while ($row = mysql_fetch_array($answer1)) {
    echo '<tr>';
    echo "<td><input name='checkbox[]' type='checkbox' id='checkbox[]' value='$row[imageven_id]'></td>";
    echo "<td><a href='$row[file_data]')'>$row[upload_name]</a></td>";
    echo "<td>$row[image_category]</td>";
    echo "<td>$row[upload_date]</td>";
    echo '</tr>';
}

Answer by Starx

Storing raw blob data is very complicated if you don’t have image type stored somewhere. I hope you have either fixed the type of image the system accepts or have stored the image type somewhere in the table too.

Any ways, when you showing images using blob data in a browser, you need to know the image type. Create a separate page to show images only. For example create showimage.php. On this page write the following code

$id= abs($_GET['id']);
$query = mysql_query("SELECT file_data FROM imagetable WHERE id='$id'");
$data=mysql_fetch_array($query);

header('Content-type: image/jpg'); //This is where we need to know the image type
echo $data['file_data'];

Now, you can link to this page to show the image, in this way

echo "<a href='showimage.php?id=".$row['id']."'>".$row['upload_name']."</a>";

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!