View Full Version : Referencing Image File Using Databases in PHP

02-27-2012, 09:05 PM
Hello all;

What I am trying to do is use a database to reference to image files I have uploaded onto my website's server space. Initially I want to draw one image from the database, and use further coding to switch that image with another image in the database. I was able to show all of the images in the database:


$sql = "SELECT owimgpath,

$result = mysql_query($sql);
$ext = ".png";

while($row = mysql_fetch_array($result, MYSQL_ASSOC))
$path = $row['owimgpath'];
$name = $row['owimgname'];
$img = $path.$name.$ext;

echo "<img src='".$img."' />";


However, I want to build the connection with the database but only show the image I want to show. Please let me know if you have any suggestions or questions as to how I want this to work. Thank you.

02-27-2012, 09:49 PM
How will you know which image to show?
Is there some sort of id or name ... something unique about the images?

You have to specify in the query which one to look for, and only find one of them.
So the thing you're seeking has to be unique for each photo.

02-28-2012, 12:25 AM
$ext = ".png";

You cannot use extensions like this.You need to pass header

Header("Content-Type: image/png");

It can be done like this:
Have 2 files,one for querying the database, another for viewing
Have a function,like your present, accepting image id,
then,query the database and get the image,
pass the image with proper headers to second file
let's assume second file is view.php
so it will have,

<img src="getimg.php?id='img_id'">

getimg.php file will query the database and show the image

02-28-2012, 05:37 AM
senidaljeet, could you possibly post some example code for the two files I should be making? and mlseim, I was figuring on using the database rows "owimgname" or "owimg_id" as an unique id to call the images.

02-28-2012, 01:24 PM
You need to first define what $owimgID is ... from a form, from a SESSION, from somewhere.

Then make it a condition of your query ...

$sql = "SELECT owimgpath, owimgname
FROM overworld
WHERE owim_id='$owimgID'
ORDER BY owimg_id";

03-01-2012, 09:23 PM
Here is the tutorial for the same,
Store images in mysql blob (http://www.techcubetalk.com/2009/01/tutorial-on-how-to-store-images-in-mysql-blob-field/)
however, i will not suggest you to go for it,even i had taken the same approach for my first project, but there's serious perfromance issues with storing images in database,
a very good explanation:
blob vs file system (http://www.webmasterworld.com/forum88/9091.htm)
You can upload the images into a folder, then have a column in the database to store the path of the image.