| | |
Displaying images from mysql database
Please support our PHP advertiser: PostgreSQL or MySQL? Compare and contrast the two most popular open source databases
![]() |
•
•
Join Date: Dec 2003
Posts: 7
Reputation:
Solved Threads: 0
I have successfully uploaded image to mysql database using a form: This is the code:
<?php
$errmsg = "";
if (! @mysql_connect("localhost","root","")) {
$errmsg = "Cannot connect to database";
}
@mysql_select_db("adim");
if(isset($_REQUEST['submit']))
{
$imgtype=$_FILES['uploadfile']['type'];
$name=$_REQUEST['name'];
$address=$_REQUEST['address'];
$dateofbirth=$_REQUEST['dateofbirth'];
if($imgtype=="image/jpeg" || $imgtype=="image/jpg" || $imgtype=="image/pjpeg" || $imgtype=="image/gif" || $imgtype=="image/x-png" || $imgtype=="image/bmp")
{
$image=$_FILES['uploadfile']['tmp_name'];
$fp = fopen($image, 'r');
$content = fread($fp, filesize($image));
$content = addslashes($content);
fclose($fp);
$sql="insert into img_tab1 (name,image,address,dateofbirth) values ('$name','$content','$address','$dateofbirth')";
$res=mysql_query($sql) or die (mysql_error());
}
}
?>
Now I need to display the row data including the image, can someone please offer a code that will solve the problem.
Thanks
Austin
<?php
$errmsg = "";
if (! @mysql_connect("localhost","root","")) {
$errmsg = "Cannot connect to database";
}
@mysql_select_db("adim");
if(isset($_REQUEST['submit']))
{
$imgtype=$_FILES['uploadfile']['type'];
$name=$_REQUEST['name'];
$address=$_REQUEST['address'];
$dateofbirth=$_REQUEST['dateofbirth'];
if($imgtype=="image/jpeg" || $imgtype=="image/jpg" || $imgtype=="image/pjpeg" || $imgtype=="image/gif" || $imgtype=="image/x-png" || $imgtype=="image/bmp")
{
$image=$_FILES['uploadfile']['tmp_name'];
$fp = fopen($image, 'r');
$content = fread($fp, filesize($image));
$content = addslashes($content);
fclose($fp);
$sql="insert into img_tab1 (name,image,address,dateofbirth) values ('$name','$content','$address','$dateofbirth')";
$res=mysql_query($sql) or die (mysql_error());
}
}
?>
Now I need to display the row data including the image, can someone please offer a code that will solve the problem.
Thanks
Austin
•
•
Join Date: May 2005
Posts: 514
Reputation:
Solved Threads: 19
basically you want to do something like this:
PHP Syntax (Toggle Plain Text)
if ($_REQUEST[your_image_var] == 1) { header("Content-type: image/jpeg"); print $bytes; exit (); }
•
•
Join Date: Feb 2008
Posts: 4
Reputation:
Solved Threads: 0
ive worked with images & mysql by uploading the file to (DIR)/upload then storing the directory only in mysql.
then using something like :-
<?php
$result=mysql_query("select * images where id = BLAH!");
$row=mysql_fetch_array($result);
?>
<html>
<body>
<img src="<?php echo $row[directory] ?>"/>
</body>
</html>
then using something like :-
<?php
$result=mysql_query("select * images where id = BLAH!");
$row=mysql_fetch_array($result);
?>
<html>
<body>
<img src="<?php echo $row[directory] ?>"/>
</body>
</html>
I have also done a bit with CMS which requires image storage on a LAMP system. Why not simply store the images in an image directory and refer to the image location in the database field. Okay it requires extra work using the file system, but to be honest I found it easier in the long run. PHP has some excellent fast functions for managing directories/files. You then retrieve and display the image as cmarkme suggests.
Anything one man can make - another man will try to break.
Way I see it is this - you need four parts to your code. For preference I'd put things like database connections and paths to file storage in constants that you can include wherever you need them. The objective is to store your images in fixed directory, give them unique names if you need to, refer to the directory using a constant (so you can use it anywhere in your script) Store only the filenames in your database then when you need an image, you simply rebuild the path and filename by recombining the constant with the result of your SQL statement.
So you define the path to your image directory thus:
define("MAIN_IMAGE_STORE","../images/");
you then need to upload and store images in this directory thus:
$whereto=MAIN_IMAGE_STORE.$_FILES['ulfile']['name'];
$result=copy($_FILES['ulfile']['tmp_name'],$whereto);
(don't forget - never trust anything uploaded to your server!!!)
you also need to extract the filename from the uploaded file thus:
$image_name=$_FILES['ulfle']['name'];
(you can do some checks here to see if the image-name already exists and inform your user accordingly)
You store this filename ONLY in the database. (You do not need to store the path - that is already set in your path constant - the beauty is if you need to change the path, you do so simply by creating the new directory and updating the constant.)
"UPDATE database_table SET my_image = '$image_name WHERE ... etc
To retrieve the image for display you create your SQL to fetch the required filename from the database, "SELECT my_image FROM database_table WHERE guid = xxxx.xxxx...." or whatever, and include this result into your IMG tag, see the code snippet given by cmarkme. HOWEVER this time you need to specify the location of the image by rebuilding the path from your constant plus the image-name you have retrieved from the database; which is of course (simplified as):
$image_name=$row['image_name'];
or...
$full_path=MAIN_IMAGE_STORE.$image_name;
or...
<img src='".MAIN_IMAGE_STORE.$image_name."' ... etc>
Obviously your choice of syntax is personal in the code snippets above. You could build the entire path and filename first, or simply concatenate the whole thing into one line of code.
There is loads of stuff on this topic in the php manual. I hope this helps, it's a bit stilted I know and there are so many possibilities, but this should point you in one direction that will work a treat and is fairly efficient both from handling the images and database frugality.
So you define the path to your image directory thus:
define("MAIN_IMAGE_STORE","../images/");
you then need to upload and store images in this directory thus:
$whereto=MAIN_IMAGE_STORE.$_FILES['ulfile']['name'];
$result=copy($_FILES['ulfile']['tmp_name'],$whereto);
(don't forget - never trust anything uploaded to your server!!!)
you also need to extract the filename from the uploaded file thus:
$image_name=$_FILES['ulfle']['name'];
(you can do some checks here to see if the image-name already exists and inform your user accordingly)
You store this filename ONLY in the database. (You do not need to store the path - that is already set in your path constant - the beauty is if you need to change the path, you do so simply by creating the new directory and updating the constant.)
"UPDATE database_table SET my_image = '$image_name WHERE ... etc
To retrieve the image for display you create your SQL to fetch the required filename from the database, "SELECT my_image FROM database_table WHERE guid = xxxx.xxxx...." or whatever, and include this result into your IMG tag, see the code snippet given by cmarkme. HOWEVER this time you need to specify the location of the image by rebuilding the path from your constant plus the image-name you have retrieved from the database; which is of course (simplified as):
$image_name=$row['image_name'];
or...
$full_path=MAIN_IMAGE_STORE.$image_name;
or...
<img src='".MAIN_IMAGE_STORE.$image_name."' ... etc>
Obviously your choice of syntax is personal in the code snippets above. You could build the entire path and filename first, or simply concatenate the whole thing into one line of code.
There is loads of stuff on this topic in the php manual. I hope this helps, it's a bit stilted I know and there are so many possibilities, but this should point you in one direction that will work a treat and is fairly efficient both from handling the images and database frugality.
Anything one man can make - another man will try to break.
Hiya nav33n, yes fully understood, just a different way of doing things I guess. As I said, there are many ways of accomplishing the same job. The OP revealed a problem with retrieval of the image and display. Using this method elegantly negates the problem by allowing insertion of a filename, constructed on-the-fly so to speak into the html img tag. Horses for courses.
Anything one man can make - another man will try to break.
![]() |
Similar Threads
- displaying image from database (PHP)
- Displaying Images( buffered data ) from the Database using Java (Java)
- help needed in coloring html tables (JavaScript / DHTML / AJAX)
- PHP Members HELP W/DB Images (PHP)
- Pagination - not displaying results properly, please help! (PHP)
Other Threads in the PHP Forum
- Previous Thread: Class Error
- Next Thread: Hi Folks
Views: 5069 | Replies: 11
| Thread Tools | Search this Thread |
Tag cloud for PHP
.htaccess access ajax apache api array beginner binary broken cakephp checkbox class cms code cron curl database date directory display download dynamic echo email error errors file files folder form forms function functions google href htaccess html if...loop image include insert integration ip java javascript joomla jquery limit link login loop mail menu methods mlm mod_rewrite multiple mysql oop parse paypal pdf php problem query radio random recursion recursive regex remote script search select server sessions shot sms soap source space speed sql structure syntax system table tutorial update updates upload url validation validator variable vbulletin video web xml youtube






