WeberDev.com PHP and MySQL Code

LOG IN
BEGINNER GUIDESPHP CLASSESCODE SEARCHARTICLES SEARCHPHP FORUMSPHP MANUALPHP FUNCTIONS LISTWEB SITE TEMPLATES
Start typing to search for PHP and MySQL Code Snippets and Articles Search


Submit a code Example / Snippet Join us on FaceBook
Submit a code Example / Snippet Submit Your Code
Search Engine Optimization Monitor SEO Monitor
Web Site UpTime Monitor UpTime Monitor
Your Personal Examples List My Favorite Examples
Your Personal Articles List My Favorite Articles
Edit Account Info Update Your Profile
PHP Code Search
Web Development Forums
Learn MySQL Playing Trivia
PHPBB2 Templates
Web Development Resources
Web Development Content
PHPClasses
PHP Editor
PHP Jobs
Vision.To Design
Ajax Tutorials
PHP Programming Help
PHP/MySQL Programming
Webmaster Resources
Webmaster Forum
XML meta language
website builder



Go Back Add a Comment Send this Article to a friend Add this Article to your personal favoritest for easy future access to your favorite Code Examples and Articles. Submit a code example Print this code example.
BACK ADD A COMMENT SEND TO A FRIEND ADD TO MY FAVORITES SUBMIT AN ARTICLE PRINT
Title : Saving Images in MySQL
Categories : MySQL, PHP, Graphics, Databases
Boaz Yahav
Boaz Yahav
Date : 1999-10-21
Grade : 4 of 5 (graded 7 times)
Viewed : 180958
Search : More Articles by Boaz Yahav
Action : Grade This Article
Tools : My Favotite Articles


Submit your own code examples 
 


Sometimes, it's more convenient to save images in a database than as files. MySQL and PHP make it very easy to do this . In this article, I will describe how to save images in a MySQL database and display them later on.



Setting up the database


The difference between any regular text or integer fields and a field that needs to save an image is the amount of data that is needed to be held in the field. MySQL uses special fields to hold large amounts of data. These fields
are known as blobs (blob).


Here is the BLOB definition from the MySQL site :


A BLOB is a binary large object that can hold a variable amount of data. The four BLOB types TINYBLOB, BLOB, MEDIUMBLOB and LONGBLOB differ only in the maximum length of the values they can hold.


For more information about MySQL BLOBs check out :

http://www.mysql.net/Manual_chapter/manual_Reference.html#BLOB

Use the next syntax to create a basic table that will hold the images:




CREATE TABLE Images (
PicNum int NOT NULL AUTO_INCREMENT PRIMARY KEY,
Image BLOB
);


Setting the upload script


An example of a file upload front end can be seen at File Uploading by berber (29/06/99). What we need now is the PHP script that will get the file and insert it into MySQL. The next script does just that. In the script, I'm assuming that the name of the file field is "Picture".


<?
If($Picture != "none") {
$PSize = filesize($Picture);
$mysqlPicture = addslashes(fread(fopen($Picture, "r"), $PSize));
mysql_connect($host,$username,$password) or die("Unable to connect to SQL server");
@
mysql_select_db($db) or die("Unable to select database");
mysql_query("INSERT INTO Images (Image) VALUES ('$mysqlPicture')") or die("Can't Perform Query");
}
else {
echo
"You did not upload any picture";
}
?>


This is all that is needed to enter the image into the database. Note that in some cases you might get an error when you try to insert the image into MySQL. In such a case you should check the maximum packet size allowed by your MySQL ver. It might be too small and you will see an error about this in the MySQL error log.

What we did in the above file is :

1. Check if a file was uploaded with If($Picture != "none").

2. addslashes() to the picture stream to avoide errors in MySQL.

3. Connect to MySQL, choose the database and insert the image.


Displaying the Images


Now that we know how to get the images into the database we need to figure out how to get them out and display them. This is more complicated than getting them in but if you follow these steps you will have this up and running in no
time.


Since showing a picture requires a header to be sent, we seem to be in an impossible situation in which we can only show one picture and than we can't show anymore Since once the headers are sent we can't send any more headers.


This is the tricky part. To outsmart the system we use two files. The first file is the HTML template that knows where we want to display the image(s). It's a regular PHP file, which builds the HTML that contains the <IMG> tags, as
we want to display them. The second file is called to provide the actual file stream from the database directly into the SRC property of the <IMG> tag.

This is how a simple script of the first type should look like:


<HTML>
<BODY>
<?
mysql_connect
($host,$username,$password) or die("Unable to connect to SQL server");
@
mysql_select_db($db) or die("Unable to select database");
$result=mysql_query("SELECT * FROM Images") or die("Can't Perform Query");
While(
$row=mysql_fetch_object($result)) {
echo
"<IMG SRC=\"SecondType.php3?PicNum=$row->PicNum\">";
}
?>
</BODY>
</HTML>


While the HTML is being displayed, the SecondType.php3 file is called for each image we want to display. The script is called with the Picture ID (PicNum) which allows us to fetch the image and display it.

The SecondType.php3 file looks like this :


<?
mysql_connect
($host,$username,$password) or die("Unable to connect to SQL server");
@
mysql_select_db($db) or die("Unable to select database");
$result=mysql_query("SELECT * FROM Images WHERE PicNum=$PicNum") or die("Can't perform Query");
$row=mysql_fetch_object($result);
Header( "Content-type: image/gif");
echo
$row->Image;
?>


This is the whole theory behind images and MySQL. The scripts in this example are the basics. You can now enhance these scripts to include thumbnails, set the images in various positions, enhance the database table to hold an ALT field, Check the width and height of the images before you insert them into the database and keep that data in the table too etc...









Creating an IE-Only Database Driven Menu System With PHP, MySQL and DHTML
Categories : PHP, MySQL, Databases, DHTML
Case Study: Handling MySQL Growth With a PHP Class
Categories : Databases, MySQL, PHP
PHP, MySQL and Authentication 101
Categories : PHP, Databases, MySQL, Authentication
Building A Persistent Shopping Cart With PHP and MySQL
Categories : PHP, MySQL, Databases, Ecommerce
Practical Date and Time examples with PHP and MySQL
Categories : Databases, MySQL, PHP, Date/time
Simple Connection to MySQL with PHP
Categories : PHP, MySQL, Databases
Alternating row colors with PHP and mySQL
Categories : PHP, Databases, MySQL, HTML and PHP
Miles To Go Before I Sleep...
Categories : PHP, Calendar, Databases, MySQL
Multicolumn Output from a Database with PHP
Categories : PHP, Databases, HTML and PHP, MySQL
Date Arithmetic With MySQL
Categories : PHP, Databases, MySQL, Date Time
Time Is Money Part 1 of 2 - Designing and implementing a Web-based application
Categories : PHP, Databases, MySQL, Complete Programs
PHP and MySQL News with Comments
Categories : PHP, Databases, MySQL
User identification using cookies in PHP and MySQL
Categories : PHP, Databases, MySQL, Cookies
Custom MySQL-functions
Categories : Databases, MySQL, PHP, PHP Functions
Watching The Web
Categories : PHP, Databases, MySQL, HTTP, MD5
Elvis Chandra wrote : 14
First thanks with this great script.
But until now, I`m still confusing about this script because cannot
run well at my computer.
It has a problem when I want to display image from mysql database to HTML.
Can You give me some information/solution about it ?
or May something wrong with my server ?
I am using Personal Web Server on Windows 95.
Thanks...
Boaz Yahav wrote : 15
Hi

It`s hard trying to figure what is wrong when you didn`t
give any clues to what is not working properly. ..
Anonymous wrote : 16
I`m working on a server which has the SAFE MODE
restriction active, so I can`t read the temporary file
which is where the upload file is stored, as the SAFE
MODE can not be deactivated for security reasons on my
server, Is there any way to do a file upload using PHP
and without the need to read the temporary folder of
the server?, for example create my own temporary folder
and having the file stored ther? ...
Anonymous wrote : 21
Can you accomplish the same thing with Perl??
Anonymous wrote : 41
seems like a nice script...:) Is it possible to run a
automatic batch processing on the pictures before they
are stored in the database....I want the the pictures to
be stored with a predefined width and hight..
sunghun choi wrote : 42
Anyone help me.
I can`t this script working..
Error .. help me.
image insert mysql db -> O.K
but, can`t show the image in the db.
Why?
Anonymous wrote : 53
You add slashes into image source. Do I need remove
them with function stripslashes() when I want to display
Image?
You don`t use it. Why?
Anonymous wrote : 54
Have problems displaying images
I am able to put images into my database but I am not
able to display them (you get the `broken image` icon)

Any ideas?
Anonymous wrote : 55
Hello!

I am having a problem. I keep on getting broken img icons.
Any comments? In addition, when I check MySQL monitor
and "select*from Images" my PicNum are showing up fine but
my Image looks like this:
------------------------------------------------------
------------------------------------------------------
------------------------------------------------------
------------------------------------------------------
------------------------------------------------------
and so on...
I thought binary data should be 0`s and 1`s. Any comments?

Thank you in advance,

Piet
Boaz Yahav wrote : 57
Broken image icons mean that the headers are not
sent. This usually happens if the headers are sent
before you expect them to be sent and when you try to
send the header for the image the header can not be
sent and the result is a broken image instead of your
image.

Look for empty lines or spaces before the line that you
send the header.

As for the pictures that show as broken lines, are you
sure you followed all of the code as expained above?
did you use the addslashes() function?
Anonymous wrote : 60
Hi,

I`m beginnig studying PHP and I`d like if Someone could
explains, How this line work:

-----
If($Picture != "none") {
$PSize = filesize($Picture);
$mysqlPicture = addslashes(fread(fopen
($Picture, "r"), $PSize));
----

I appreciate anyone who answer.
Boaz Yahav wrote : 61
If you chose a picture to upload in the form:

If($Picture != "none"),

Get the picture dimensions :

$PSize = filesize($Picture); (this is an array)

Add Slashes to the binary string, e.g. escape special
chars:

$mysqlPicture = addslashes(fread(fopen ($Picture, "r"),
$PSize));

Taco Ekkel wrote : 62
Storing files in a DB is definitely the way to go, i
successfully used it in a lot of environments and file
types before (great for file consitency, file checking,
etc.). However, one problem remains. When directly
outputting a file, one would first print a content type
header:

content-type: application/vnd.ms-powerpoint

or something. However, I have not yet discovered how
to properly give file a name. If you choose `save target
as...` or if the browser doesn`t recognize the MIME type
it displays a `save as`dialog box with `getfile.php4` as
the name of the file (or worse:
`?fileID=7166&encapsulate=off&compress=off`)

I have digged all the way through W3C`s HTTP protocol
to find a HTTP field like `Content-Name` but it does not
seem to exist.

Ideas, Anyone?

(and about the strip/addslashes question i saw above:
sometimes you do need to use both, sometimes you
don`t.... depends on the server settings! It`s in php.ini,
the section with gpc_magic_quotes; always check this
before uploading your php scripts to a server you`re not
familiar with)
Boaz Yahav wrote : 63
I think what you mean is :


header("Content-Disposition: attachment; filename=MyFile.php");


berber
Nedelcu Eugen wrote : 70
man this site ownz .....
Anonymous wrote : 73
Thank you first!If the user submit a different type
of picture,such as .psd,.tif,what can I do?
Boaz Yahav wrote : 74
I`m not sure what you want to do... Browsers don`t
usually show pictures of type PSD and such. you should
instruct your users to use gif or jpg files only.

If you intend to use the data in other places than
browsers than you should know what you plan to do
with it...
Anonymous wrote : 80
I thought this script had solved my image display
problems. But I can not seem to get it to work.

The image is in the db. I can get it out onto a page by
itself quit happily.

But when I call the second script from an src tag, all i
ever get is broken links.

Any ideas?


H
Boaz Yahav wrote : 83
Wierd, this works great for me.
You should check if the URL in the second src
is leading you to a page with a picture by it`s self.

You should be able to display any number of images on
the same page using this method.

berber
Anonymous wrote : 97
Hi
I can use some help here.
up loading to the DB was OK, Getting the darn Image to
the web page was something else. the only thing that i
did to the script was changing the name of the
SecondType.php3 To type.php3.
and i found that the script is not calling the type.php3 at
all . i did check the spelling and make sure that the file
is in the same folder and still it`s not being called . and
to make sure of that, i removed the file
compleatly "type.php3" and i still get the same result.
the images are in the DB i did check to make sure. here
is the source of the page that should have the image on
it .
<HTML>
<BODY>
<IMG SRC="type.php3?
PicNum="><IMG SRC="type.php3?
PicNum=">
</BODY>
</HTML>
any idea to what i am doing worng.
thanks a million
sam.
Boaz Yahav wrote : 98
The name of the file is not relevant as long as you also
change it in the <IMG SRC=...>.

How do you know it`s not called? cause you don`t see
the picture? or do you get an 404 error?
Anonymous wrote : 99
Thanks for the reply.
After a checked the script line for line and word for word
and all what i was getting was three little boxes in the
web page and if i add more images to the database
more little boxes show in the web page "broking
links",so i erased some lines in the type.php3 file and i
got the same result and no error messages so i
renamed the type.php3 file to ttype.php3 to see if i am
going to get any errors and to my surprise i did`t so that
what got me thinking that the file is not being called . if
it was called and it is not there i should get an error of
some kind ........Right.
Thanks again
sam
Boaz Yahav wrote : 100
My guess is that you either don`t have error_reporting()
set to display errors and you have "white spaces"
somewhere in the type.php3 causing the headers to be
sent prematurely or you really don`t call the file. In the
later, you can simply look in the apache logs to see an
404 (File not found) entry or in the error log.
Anonymous wrote : 101
How can I check the height and width of an image-file??
Boaz Yahav wrote : 102
To find the dimentions of a picture you can use
something like this :

Assuming that $Picture is the variable of the picture
uploaded :
$PictureData=GetImageSize($Picture);
$PSize = filesize($Picture); // Get the file Size
$PWidth = $PictureData[0]; // Get the Picture Width
$PHeight = $PictureData[1]; // Get the Picture Height
$PFormat = substr($Picture_name, strlen($Picture_name)-3, 3); // Get the file extension.
$mysqlPicture = addslashes(fread(fopen($Picture, "r"), $PSize)); // Get the picture ready to
// insert into a db.
?>
Anonymous wrote : 103
Hi
I finaly got the script to work right
" there is nothing wrong with the script "
And thanks alot for it .
Sam nabass
Harald Zischg wrote : 105
Hi Yahav,

thank`s a lot for your script!
I`ve been looking for this solution quite a time...

The only thing I had to change to make it work for me,
is the SecondType.php3, because I also got broken links
like some of the folks above.
I`ve added the database-open commands just like in
the other 2 php files - and oops it worked.

Thank`s again and keep on phping!
Harald.
Boaz Yahav wrote : 106
Obviously you are correct. I made a mistake to think this
is trivial and that everybody will do it. I just made a
change to the script and I hope it will save some of the
problems.

berber
ole wrote : 117
Hi!
I am working on Win98.
I get the following errors and cannot figure out what is
wrong:
Warning: fopen("\\php2","rb") - Unknown error in
c:\apacheserver\apache\www\sosu\html\update\pers_u
pdate.php on line 13
Warning: Unable to find file identifier 0 in
c:\apacheserver\apache\www\sosu\html\update\pers_u
pdate.php on line 13

... here we go:
<?PHP
IF ($submit) {
IF ($picture != "none") {
include("../db_vari.php");

$PSize = FILESIZE($picture); // Get the file Size
$mysqlPicture = ADDSLASHES(FREAD(FOPEN
($picture, "rb"), $PSize)); // Get the picture ready to
insert into a db

mysql_connect($host,$username,$password) or die
("Unable to connect to SQL server");
mysql_select_db($database) or die ("Unable to select
database");
$query = MYSQL_QUERY("INSERT INTO pict_test
(pict)"."VALUES (`$mysqlPicture`)");
}
}
?>

<FORM METHOD="post" ACTION="<?php ECHO
$PHP_SELF; ?>" enctype="multipart/form-data">
<INPUT TYPE="hidden" NAME="MAX_FILE_SIZE"
VALUE="1000000">
<BR>Your picture:<BR>
<INPUT TYPE="file" NAME="picture" SIZE="40">
<INPUT TYPE="submit" NAME="submit"
VALUE="Upload">
</FORM>
...please HELP!
Ole, Denmark
Paul Chambers wrote : 130
I`m also getting errors trying to locate the PHP
temporary folder.

My understanding is that :

1. a simple HTML file upload form uploads the file to the
server`s temporary folder then issues a variable
indicating the directory path

2. this path is used in the fopen command to locate the
uploaded file, gather the data to submit to the
database.

My problem is that when the fopen / fread command
looks for the tmp folder - it can`t find it.

Is there a way to specify where the file is uploaded to
(without altering the php.ini - because I don`t have
control over that) ?
Anonymous wrote : 131
The script is good .. but it is giving me a broken link
when I execute it. The image is getting stored in the
database.. Also there are no spaces in front of the
header..I tried out all the checks..Following is my
header code.
<?

$result=mysql_query("SELECT * FROM Images WHERE
PicNum=`$PicNum`")or die("Can`t perform Query");
$row=mysql_fetch_object($result);
Header("Content-type : image/GIF89a");
echo $row->Image;
?>

Please give a solution..

Thank u.
James Salinas wrote : 161
This is definitely very useful!
As all others did, I had to do a couple of changes here &
there, but the base code example you provided above
covers everything that is basically needed!

Thanx for posting this!

(note to self: scratch vacation plans... you`ll be sittin at
the computer 24/7 for that week now...)
macgruder ross wrote : 166
This is similar to a script that I`ve been using. Is there a way to adapt it
so that I can upload two or three pictures at the same time. Is the
following sufficient:

$mysqlPicture1 = addslashes(fread(fopen
($Picture1, "r"), $PSize1));
$mysqlPicture2 = addslashes(fread(fopen
($Picture2, "r"), $PSize2));
Anonymous wrote : 192
how can i retrieve a picture from my-sql database?
Anonymous wrote : 208
For the filename problem I added a column to my table,
after this was suggested by a local guru (ASP... tsk):

my SQL query now reads;

$result=MYSQL_QUERY("INSERT INTO binary_data
(description,bin_data,filename,filesize,filetype) ".
"VALUES
(`$form_description`,`$data`,`$form_data_name`,`$form_d
ata_size`,`$form_data_type`)");

$form_data_name, $form_data_size and
$form_data_type are all defined when you hit the
upload button.

Obviously I named my the file field "form_data". This
might be helpful to someone?


(on a side note, you have to retrieve the filename,
filesize and filetype in a seperate action to your show
image file or function - or your headers`ll be messed up)


Anonymous wrote : 232
Man...I must be the biggest idiot on the web. Can you please
tell me why my code does not work?
Thank You very much!!!

I`m using PHKat (ultradev).

This file is called displayimage.php

<html>
<head>
</head>
<body bgcolor="#FFFFFF" text="#000000">
<?php
echo "<IMG SRC=\"GetImage.php?paramID=1\">";
?>
</body>
</html>



This file is called getimage.php:

<?php
require("./../adodb/adodb.inc.php");
require("./../Connections/prague_ODBC.php");

$Image_ID = "1";
if (isset($paramID))
{$Image_ID = $paramID;}

$Selected_Image=$prague_ODBC->Execute("SELECT Image FROM image WHERE Image_ID = " .
($Image_ID) . "") or DIE($prague_ODBC->ErrorMsg());
header("Content-type: image/gif");
echo $Selected_Image->Fields("Image");
?>


I get no errors and the broken image link.
I am completely fustrated and clueless as to why it does not work.

Thanks for your help
Anonymous wrote : 233
Oh, and the getimage.php file
works fine if you run it.

:)

Also, can you explain why those 2 files don`t
work together?

Thanks
Neetu Kumar wrote : 242
Can u plz guide me how to use the same funcatnality
with JSP code ie storing Images in a MySQL Database.
neeraj kinger wrote : 245
Hi Yahav
i am trying to print images on my web browser
getting the name right but image displayed is cross
sign image with all having same size i.e 28*30.
<HTML>
<BODY>
<?
mysql_connect(`localhost`,`test`)
or die("Unable to connect to SQL server");
@mysql_select_db(`ladakh_chamber`)
or die("Unable to select database");
$result=mysql_query("SELECT * FROM malt_photo")
or die("Can`t Perform Query");
While($row=mysql_fetch_object($result)) {
echo "<IMG SRC="getdata01.php?
comp_name=$row->Company_Name">";
}
?>
</BODY>
</HTML>
please help me
thanks

Anonymous wrote : 247
my server seems to be very slow at loading the images
sometimes they dont load at all if I saved just the url to
the picture in mysql what would the code look like to
display teh picture then?

Thanks in advance
Anonymous wrote : 248
my server seems to be very slow at loading the images
sometimes they dont load at all if I saved just the url to
the picture in mysql what would the code look like to
display teh picture then?

Thanks in advance
Anonymous wrote : 249
my server seems to be very slow at loading the images
sometimes they dont load at all if I saved just the url to
the picture in mysql what would the code look like to
display teh picture then?

Thanks in advance
Anonymous wrote : 254
Can someone take a look a my script. For some
reason the pictures wont take.

The script can be seen working here------->
http://undergroundvending.com/imageupload/Picture
.php

Picture.php (uploading the pictures)
-----------------------------------------------------
<?
require("login.inc");

$conn=mysql_pconnect($host,$user,$pwd)
or die("Unable to connect to SQL server");
mysql_select_db($db,$conn)
or die("Unable to select database");


If($Picture != "none") {
$PSize = filesize($Picture);
$mysqlPicture = addslashes(fread(fopen
($Picture, "r"), $PSize));

mysql_query("INSERT INTO Images (Image)
VALUES (`$mysqlPicture`)")
or die("Can`t Perform Query");
}
else {
echo"You did not upload any picture";
}
?>


<html>
<head>
<title>Visual Uploads</title>
<meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1">

<link rel="stylesheet" href="../UGVstyle.css"
type="text/css">
</head>

<body bgcolor="#FFFFFF" text="#000000">


<FORM METHOD="post" ACTION="<?php ECHO
$PHP_SELF; ?>" enctype="multipart/form-data">

<BR>Your picture:<BR>
<INPUT TYPE="file" NAME="picture" SIZE="30">
<INPUT TYPE="submit" NAME="submit"
VALUE="Upload">
</FORM>

<a href="show.php"><font color="#837063">View
Pictures</font></a>
</body>
</html>
------------------------------------------------------


show.php (show pictures)
-------------------------------------------------------
<HTML>
<BODY>
<?
require("login.inc");

$conn=mysql_pconnect($host,$user,$pwd)
or die("Unable to connect to SQL server");
mysql_select_db($db,$conn)
or die("Unable to select database");

$result=mysql_query("SELECT * FROM Images")
or die("Can`t Perform Query");
While($row=mysql_fetch_object($result)) {
echo "<IMG SRC=\"secondtype.php?
PicNum=$row->PicNum\">";
}
?>
</BODY>
</HTML>

-------------------------------------------------------


secondtype.php (second script for show)
---------------------------------------------------
<?
require("login.inc");

$conn=mysql_pconnect($host,$user,$pwd)
or die("Unable to connect to SQL server");
mysql_select_db($db,$conn)
or die("Unable to select database");

$result=mysql_query("SELECT * FROM Images
WHERE
PicNum=$PicNum") or die("Can`t perform Query");
$row=mysql_fetch_object($result);
Header( "Content-type: image/gif");
echo $row->Image;
?>
-------------------------------------------------------

Thanks for any help with this!!

Anonymous wrote : 259
give to me!
pat chriswick wrote : 262
hi there looks like i am having the same problems
as most other people i can get the file stored on the
database no problem. I just can`t get them back out
again i just get the brocken image icon i am using
the addslashes function there are no whitespace
characters or empty lines before my
Header("Content-type:image/gif");
line can anyone help me please!! i am using php4
on win98 se many thanks for any help you can offer
best wishes pat
pat chriswick wrote : 267
here`s a fix for all those people having problems
with retrieving images from their database windows
does not automatically recognise binary files so
put "rb" instead of "r" in your script i.e. read binary
this worked for me best of luck
David Perez wrote : 281
Hi i tryed this script into w2k , but the mysql for w2k
always cut the file at 802 bytes the maximun paked size
is set to 10M any idea to helpme?
matthew waygood wrote : 282
TO SAVE TO DATABASE
$file = fopen($form_image, "rb");
$bin_data = fread($file, $form_image_size);
$bin_data = addslashes($bin_data);

$result=MYSQL_QUERY("INSERT INTO images
(image_name,image_type,image_size,image_width,imag
e_height,image_binary) ".
"VALUES
(`$form_image_name`,`$form_image_type`,`$form_image
_size`,$width,$height,`$bin_data`)");


This is the code I am using and it works so feel free to
use it.

TO DISPLAY
run the query to bring back the type and the binary
$type = mysql_result($result,0,$type_row);
Header("Content-type: $type");
echo mysql_result($result,0,$image_row);


YOU do not remove slashes when displaying

P.S. PHP have dropped gif support, so manipulation
can`t be done without adding in another module or
useing an old version.
matthew waygood wrote : 283
OOOpps
forgot to say that height and width are set with :-
$imageInfo = getimagesize($form_image);
$width = $imageInfo[0];
$height = $imageInfo[1];

And the $form_image_xxxxxxxx variables are
automatically set when you do a fopen
Anonymous wrote : 284
Great script! I thought adding images for my users was
going to be difficult, but this script made it really easy.
Thanks again!
Forest Runner wrote : 288
Nice scripts, but can`t get the Picture to display. As the other folks, I get broken links. Have tried
modifying the fopen() to "rb". Is there something obvious I`m not seeing...
Thanks very much.
Jim
Guy dubarry wrote : 296
Hello
I have created the table and have tried to execute the
script to upload an image,but all I get is error messages
in my browser,here they are it seems to be on the
addslashes line
Warning: fopen("","r") - No such file or directory
in /usr/local/plesk/apache/vhosts/bible-
school.co.uk/httpdocs/imgins.php on line 10

Warning: Supplied argument is not a valid File-Handle
resource in /usr/local/plesk/apache/vhosts/bible-
school.co.uk/httpdocs/imgins.php on line 10
any help will be welcome
Guy
Anonymous wrote : 299
okay i have tried to make this work in my picture
database but with no success. let me send you a
couple code snippets and i hope you are still reading
this...

here is the code that inserts the picture into the
database:

$sql = "INSERT INTO picindex
(pic_IDX,pic_OWNDERID,pic_FILENAME,pic_TITLE"

.",pic_DESC,pic_TYPE,pic_STORED,pic_ACCESS
ED,pic_SIZE,pic_THUMB,pic_FULL) "
." VALUES ("

."`$GalID`,`1`,`$fnamex`,`$PicTitle`,`$PicDesc`,`$I
mType`,`"
.date("Y-m-d H:i:s") . "`,`"
.date("Y-m-d
H:i:s") . "`,`$fsize`,`"
.addslashes(fread(fopen
("xyzzzzzz","r"), filesize("xyzzzzzz"))) . "`,`"
.addslashes(fread(fopen
($userfile,"r"), filesize($userfile))) . "`)";

the last 2 are the pictures in the database they are
both defined as type blob. the "xyzzzzzz" is a temp file
i make which is a thumbnail automatically generated
during the process by GD. the $userfile is the name of
the file that was upload by the user. the code earlier
up in the script tests for the picture being uploaded and
aborts if it wasn`t, the database is opened above as
well. i then call:

$result = mysql_query($sql,$link) or die("something icky
happened");

$link is the open database.

and lastly here is the entire picture display script it`s
pretty small.

$sql_host = "mysql-db-host";
$sql_dbas = "picture_database";
$sql_user = "mysql-user";
$sql_pass = "mysql-pass";

$link = mysql_pconnect
($sql_host,$sql_user,$sql_pass) or die("Couldnt
Connect!");;
$db = mysql_select_db($sql_dbas,$link);
$sql = "SELECT * FROM picindex WHERE
pic_ID=$ndx";
$result = mysql_query($sql) or die("Eeek!
bad Stuff happened!");
$row = mysql_fetch_object($result);
$lent = mysql_fetch_lengths($result);
if ($xstl == "t") {
if ($row->pic_TYPE == "jpg") {
header("Content-type: image/jpeg"); }
if ($row->pic_TYPE == "gif") {
header("Content-type: image/gif"); }
if ($row->pic_TYPE == "png") {
header("Content-type: image/png"); }
if ($row->pic_TYPE == "bmp") {
header("Content-type: image/bmp"); }
echo $row->pic_THUMB;
}
if ($xstl == "f") {
if ($row->pic_TYPE == "jpg") {
header("Content-type: image/jpeg"); }
if ($row->pic_TYPE == "gif") {
header("Content-type: image/gif"); }
if ($row->pic_TYPE == "png") {
header("Content-type: image/png"); }
if ($row->pic_TYPE == "bmp") {
header("Content-type: image/bmp"); }
echo $row->pic_FULL;
}

i call this routine like this pixdisp.php?ndx=id&xslt=?

xslt tells the script wether on not i want the thumbnail
image from the database (t) or the fullsize image (f).
stored in the database are both from the picstore.php
routine. pic_TYPE is collected from either the mime type
supplied by the browser or is supplied by the user.

it doesn`t work, i get broken images. any suggestions?
i`ve tried in the storing to read the picture data into a
variable like $full=fread... and $thumb=fread... that
didn`t worth either. i`m totally stumped, help?

Meeka
Juan Pablo Marichal wrote : 310
This script works great for me, though I wonder how to do some other
tasks. First, it would be better if it would restrict the users to upload heavy
files or another file that jpg, gif or png. Second, and most important for
me:

I want to use this script for setting a thumbnail gallery. I
would like to know how can I do to resize the image before storing it in the
database. This way, I can make two inserts, one for the thumbnail and
other for the image, both resized before storing them. How can I resize
the image on the fly before inserting in the database?
Jimmy Vinueza wrote : 315
great
michal grocholski wrote : 323
How can I resize images displayed from MySQl?
I do not mean simply resize like <img
src="image.php?id=50 width=xx height=xx>
but resize with ImageCopyResized function (to
decrease weight of thumbnail)

While I use this function with files stored on disk
there`s no problem but when I try to use images
from MySql there`s error "Unable to
open "image.php?id=50 for reading."

Can you suggest something?
Thank`s a lot!


juan Yamakawa wrote : 341
Hello :
This examples is`t very nice, thank a lot for explain how
to insert a archive in mysql.
Liviu Sārb wrote : 349
Hi,

Great script but...
It works fine on Win 2000 Professional with Apache 1.3.12
and PHP 4.1.1, not on Win 98 same Apache, same PHP. It
seems that SecondType.php3 does not see the $PicNum
parameter. Why?

Thanks
shamvil ahamed wrote : 351
Hello
I have created the table and have tried to execute the
script to upload an image,but all I get is error messages
in my browser,here they are it seems to be on the
addslashes line
Warning: fopen("","r") - Invaid argument in
c:\..\..\insert.php on line 10

Warning: Supplied argument is not a valid File-Handle
resource in c:\..\..\insert.php on line 10
Pl anyone help me out...
Nishad
Alex T wrote : 360
I wrote my own script for this. And it worked somewhat.
Until I wanted to use your example of
echo "<IMG SRC=\"test6.php?PicNum=$row->PicNum\">";
I wanted to have the ability to call by defining
http://***/example.php?PicNum=ANYNUMBERHERE
But it would not work in my script. So i Used yours to
figure it out step by step. And it still will not call by
using that syntax.

It works fine if I define $PicNum as a numeric.
$result = mysql_query("SELECT * FROM Images WHERE
PicNum=2") or die("die mofo query");
instead of
$result = mysql_query("SELECT * FROM Images WHERE
PicNum=$PicNum") or die("die mofo query");

It will call the image correctly every time. But using
$PicNum it will just die on me and give me the great Red X.


Am I defining the PicNum too late? When using.
echo "<IMG SRC=\"test6.php?PicNum=$row->PicNum\">";

Im clueless now, as that should work fine. It just refuses
to on my system. :/

Thanx for any help.
shah hussain wrote : 373
I am trying to upload an image to mysql server, i have created a
database and added a table called image
using this code successfully.
<?php


// open the connection

$conn = mysql_connect
("mycomputer", "user", "mctoolslab");

// pick the database to use

mysql_select_db("images",$conn);

// create the sql statement

$sql = "CREATE TABLE Image (PicNum int NOT NULL
AUTO_INCREMENT PRIMARY KEY,
Image BLOB)";



// execute the sql statement

$result = mysql_query($sql, $conn) or die(mysql_error());

// echo the result identifier

echo $result;

?>


Now i want to upload an image to my new blob table called
image
i am using the following code

<?
if($Picture != "C:\Program Files\Apache Group\Apache2
\htdocs\2cut70nc.jpg") {






$PSize = filesize($Picture); // Get the file Size



$mysqlPicture = addslashes(fread(fopen($Picture, "r"),
$PSize));

mysql_connect($mycomputer,$user,$mctoolslab) or die
("Unable to connect to SQL server");

mysql_select_db($images) or die ("Unable to select
database");

mysql_query("INSERT INTO image (Image) VALUES
(`$mysqlPicture`)") or die

("Can`t perform Query");

}
else {
echo"You did not upload any picture";
}
?>

I get an error

Warning: fread(): supplied argument is not a valid stream
resource in C:\Program Files\Apache Group\Apache2
\htdocs\upload.php on line 18
Unable to select database

Whats the problem, have i referenced my image corrcetly
regards Hussain
shah hussain wrote : 374
hello again yohev, i have made some alterations still not
working right

here is code..


<?
if("2cut70nc.jpg" != "none") {


$PSize = filesize("2cut70nc.jpg"); // Get the file Size


$mysqlPicture = addslashes(fread(fopen
("2cut70nc.jpg","rb"), $PSize));


mysql_connect(`mycomputer`, `user`, `mctoolslab`) or die
("Unable to connect to SQL server");


@mysql_select_db(`images`) or die ("Unable to select
database");


mysql_query("INSERT INTO image (Image) VALUES
(`$mysqlPicture`)") or die


("Can`t perform Query");

}
else {

echo"You did not upload any picture";
}

?>
BUFFY New Zealand wrote : 390
Hi all, thanks to the author, who i think isn`t keeping up
with all these requests! I havent got the upload working but
the displaying of images is, great script for displaying
more then one product.

WORKING EXAMPLE
-----------------------------

1. Firstly create your database accordingly!

2. Open up the php page you wish to display the images in,
notice the use of -> pointers because the example is using
mysql_fetch_OBJECT which requires this method to access the
images, you cannot use $row(ProductName) has to be ->

CODE:
<table width="80%" border="0" align="center"
cellpadding="5" cellspacing="5" id="Products">
<tr>
<td width="25%">
<?
include `inc/connect.inc.php`; //code to connect to database
$result = mysql_query(`SELECT * FROM product`)
or die("Can`t perform query");

While($row=mysql_fetch_object($result))
{
$productid = $row->ProductID;
$_SESSION[`productid`] = $productid;
echo "<img src=\"images.php?productid=$row->ProductID\">";
?> </td>
<td width="75%"><div align="left">
<?php echo $row->ProductName . "<br/>";
echo $row->ProductName2 . "<br/>";
echo $row->ProductCode . "<br/>";
echo $row->ProductDescriptionSmall . "<br/>";
echo "productid session: " . $_SESSION[`productid`];
//the following form displays a page for my large images as
this example is displaying a thumbnail
?><form>
<input type=button value="View Large Image"
onClick="window.open(`<?PHP echo
"imagebig.php?productid=$productid"?>`,`<?php echo
$row->ProductName;
?>`,`width=420,height=550,directories=no,location=no,menubar=no,scrollbars=no,status=no,toolbar=no,resizable=no,left=200,top=50,screenX=200,screenY=50`);return
false">
</form>
</div></td>
</tr>
<tr>
<td><?php
} //end first while2
?></td>
<td><div align="left"></div></td>
</tr>
<tr>
<td> </td>
<td><div align="left"></div></td>
</tr>
</table>

3. Next open up the php page you referenced ahead, in my
example its images.php

CODE:
<?php
//include file to allow multiple images to be displayed
include `inc/connect.inc.php`;
$result=mysql_query("SELECT * FROM Product WHERE
ProductID=$productid") or die("Can`t perform Query");
Header( "Content-type: image/jpeg");
$row=mysql_fetch_object($result);
echo $row->ProductImageSmall;
?>

Hopefully that helps someone.....

If your interested in the code i used for my popup window
page its below, basically just the above code slightly modified:

POPUP PAGE CODE (imagebig.php):
<?php
//include file to allow multiple images to be displayed
include `inc/connect.inc.php`; //connect to database
//query to display a image
$result=mysql_query("SELECT * FROM Product WHERE
ProductID=$productid") or die("Can`t perform Query");
Header( "Content-type: image/jpeg");
$row=mysql_fetch_object($result);
echo $row->ProductImageBig;
?>



BUFFY
:)
gilly davidson wrote : 412
I am having problems with getting this working.

I have uploaded the data ok but cannot view the image back in a web page I get this message

PicNum\">"; } ?>

I have the following set up. Sorry but a beginner at PHP, I am using Dreamweaver CS4 with mysql database

VIEW.PHP file where I am planning to view the image



mysql_connect($host,$username,$password) or die("Unable to connect to SQL server");
@mysql_select_db($db) or die("Unable to select database");
$result=mysql_query("SELECT * FROM Images") or die("Can't Perform Query");
While($row=mysql_fetch_object($result)) {
echo "PicNum\">";
}



?>




AND THE SecondType.php3


if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
if (PHP_VERSION < 6) {
$theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
}

$theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

switch ($theType) {
case "text":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "long":
case "int":
$theValue = ($theValue != "") ? intval($theValue) : "NULL";
break;
case "double":
$theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
break;
case "date":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "defined":
$theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
break;
}
return $theValue;
}
}

mysql_select_db($database_secondtype, $secondtype);
$query_Recordset1 = "SELECT * FROM images";
$Recordset1 = mysql_query($query_Recordset1, $secondtype) or die(mysql_error());
$row_Recordset1 = mysql_fetch_assoc($Recordset1);
$totalRows_Recordset1 = mysql_num_rows($Recordset1);
?>
mysql_connect($host,$username,$password) or die("Unable to connect to SQL server");
@mysql_select_db($db) or die("Unable to select database");
$result=mysql_query("SELECT * FROM Images WHERE PicNum=$PicNum") or die("Can't perform Query");
$row=mysql_fetch_object($result);
Header( "Content-type: image/gif");
echo $row->Image;
?>
mysql_free_result($Recordset1);
?>