Wrox Programmer Forums
| Search | Today's Posts | Mark Forums Read
PHP Databases Using PHP in conjunction with databases. PHP questions not specific to databases should be directed to one of the other PHP forums.
Welcome to the p2p.wrox.com Forums.

You are currently viewing the PHP Databases section of the Wrox Programmer to Programmer discussions. This is a community of software programmers and website developers including Wrox book authors and readers. New member registration was closed in 2019. New posts were shut off and the site was archived into this static format as of October 1, 2020. If you require technical support for a Wrox book please contact http://hub.wiley.com
  #1 (permalink)  
Old February 7th, 2004, 08:04 PM
Authorized User
 
Join Date: Sep 2003
Location: , , .
Posts: 18
Thanks: 0
Thanked 0 Times in 0 Posts
Default upload files

how can upload files (images in this case)in mysql databse with php?

  #2 (permalink)  
Old February 8th, 2004, 09:37 PM
richard.york's Avatar
Wrox Author
Points: 5,506, Level: 31
Points: 5,506, Level: 31 Points: 5,506, Level: 31 Points: 5,506, Level: 31
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Jun 2003
Location: Camby, IN, USA.
Posts: 1,706
Thanks: 0
Thanked 6 Times in 6 Posts
Default

Hi Joeore,

1.) Set up a field containing a unique ID
2.) Set up a BLOG field for the file data.
3.) Set up a VARCHAR mime type field if you will be storing more than one type of file.

Optional.. add fields for file name or other details.

Basically you need to extract the binary data from the file using a few PHP functions, addslashes, file will be kept in a normal variable, and then inserted like you would insert any other type of data.

// Read the contents of the file into a variable, addslashes for DB insertion
// where 'userfile' is the name of the upload field
// file_get_contents PHP 4 >= 4.3.0

$file = addslashes(file_get_contents($_FILES['userfile']['tmp_name']));
$mime = $_FILES['userfile']['type'];

if (false === ($query = mysql_query("INSERT INTO `files` VALUES(null, '{$file}', '{$mime}')")))
{
    echo 'insertion failed';
}

Here is another method which does the same as the above:
// Read the contents of the file into a variable, addslashes for DB insertion.
$file = addslashes(fread(fopen($_FILES['userfile']['tmp_name'], 'r'), filesize($_FILES['userfile']['tmp_name'])));

The following is what you do to retrieve the contents of the file:

<?php
// if passing the ID via GET
if (isset($_GET['id']))
{
    $id = $_GET['id'];
}

// get_file.php
// Make SELECT query
$data = mysql_fetch_array(mysql_query("SELECT `file`, `mime` FROM `files` WHERE `id` = '{$id}'"), MYSQL_ASSOC);

// Set the content type header
header('Content-type: {$data['mime']}');

// Also notice that I am not stripping the slashes,
// Doing so may corrupt data in certain file types,
// while you may need to do so for others.
echo $data['file'];
?>

Then simply include a link to the PHP file...
For images,
<img src='get_file.php?id=5' />

Be extra careful about resource consumption here, it may be both more efficient and practical to simply store the file in a directory file system!

: )
Rich

:::::::::::::::::::::::::::::::::
Smiling Souls
http://www.smilingsouls.net
:::::::::::::::::::::::::::::::::
  #3 (permalink)  
Old February 9th, 2004, 01:03 AM
Friend of Wrox
Points: 2,570, Level: 21
Points: 2,570, Level: 21 Points: 2,570, Level: 21 Points: 2,570, Level: 21
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Jun 2003
Location: San Diego, CA, USA
Posts: 836
Thanks: 0
Thanked 0 Times in 0 Posts
Default

"BLOG" type, eh Rich? =)



(I think he meant "BLOB"...)



Take care,

Nik
http://www.bigaction.org/
  #4 (permalink)  
Old February 9th, 2004, 02:13 PM
richard.york's Avatar
Wrox Author
Points: 5,506, Level: 31
Points: 5,506, Level: 31 Points: 5,506, Level: 31 Points: 5,506, Level: 31
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Jun 2003
Location: Camby, IN, USA.
Posts: 1,706
Thanks: 0
Thanked 6 Times in 6 Posts
Default

HaHa! Yes I meant BLOB.

: )
Rich

:::::::::::::::::::::::::::::::::
Smiling Souls
http://www.smilingsouls.net
:::::::::::::::::::::::::::::::::
  #5 (permalink)  
Old February 9th, 2004, 06:31 PM
Authorized User
 
Join Date: Sep 2003
Location: , , .
Posts: 18
Thanks: 0
Thanked 0 Times in 0 Posts
Default

thank you..but..i'm not very expert in php..can you tell me an example?:)..

joeore

  #6 (permalink)  
Old February 9th, 2004, 08:09 PM
richard.york's Avatar
Wrox Author
Points: 5,506, Level: 31
Points: 5,506, Level: 31 Points: 5,506, Level: 31 Points: 5,506, Level: 31
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Jun 2003
Location: Camby, IN, USA.
Posts: 1,706
Thanks: 0
Thanked 6 Times in 6 Posts
Default

Joeore,

1.) Set up the MySQL table

CREATE TABLE `files` (
    `id` INT( 11 ) NOT NULL AUTO_INCREMENT ,
    `file` MEDIUMBLOB NOT NULL ,
    `mime` VARCHAR( 50 ) NOT NULL ,
    PRIMARY KEY ( `id` )
);

2.) Write HTML/PHP

Basically only two fields are required to upload a file, a 'file' input field, and a 'MAX_FILE_SIZE' hidden field. The latter isn't really required, but will prevent the user from trying to upload a file that is too large on the client-side. This can be easily circumvented by the user and should be accompanied by server-side file validation. It accepts a file size in Bytes, I have set this to accept a file of 10000 bytes, or roughly 10KB. And one attribute *must* appear in the form tag to get the browser to upload data, enctype='multipart/form-data'.

The following should be pretty straight forward. It has been tested and works for me!

Code:
<?php

    //upload2db.php

    if (!isset($_POST['do_action']))
    {
        echo "<html>\n",
             "    <head>\n",
             "        <title>UPLOAD TO DATABASE</title>\n",
             "    </head>\n",
             "    <body>\n",
             "        <form action='{$_SERVER['PHP_SELF']}' method='post' enctype='multipart/form-data'>\n",
             "            <input type='file' name='userfile' />\n",
             "            <input type='hidden' name='MAX_FILE_SIZE' value='10000' />\n",
             "            <input type='submit' name='do_action' value='Upload' />\n",
             "        </form>\n",
             "    </body>\n",
             "</html>";
    }
    else
    {
        if (isset($_FILES['userfile']['tmp_name']))
        {
            if (($_FILES['userfile']['size'] <= 10000) && ($_FILES['userfile']['type'] == 'image/jpeg' || $_FILES['userfile']['type'] == 'image/pjpeg'))
            {
                // Make a database connection here!
                $link = mysql_connect('localhost', 'user', 'pass');
                mysql_select_db('test', $link);

                // file_get_contents() PHP >= 4.3.0
                $file = addslashes(file_get_contents($_FILES['userfile']['tmp_name']));

                // If using PHP < 4.3.0 use the following:
                // $file = addslashes(fread(fopen($_FILES['userfile']['tmp_name'], 'r'), filesize($_FILES['userfile']['tmp_name'])));

                if (!mysql_query("INSERT INTO `files` VALUES(null, '{$file}', '{$_FILES['userfile']['type']}')", $link))
                {
                    // do database error reporting here... 
                    echo 'Upload failed: Unable to insert image into database.';
                }
                else
                {
                    echo "Upload successful! <a href='viewdbfile.php?id=".mysql_insert_id()."'>Click here to view the file!</a>\n";
                }
            }
            else
            {
                echo 'Upload failed: File must be a JPEG file type and 10KB or less in size';
            }
        }
        else
        {
            echo 'Upload failed: A valid file has not been uploaded!';
        }
    }
?>


<?php
    // viewdbfile.php

    // if passing the ID via GET
    if (isset($_GET['id']))
    {
        $id = $_GET['id'];
    }

    $link = mysql_connect('localhost', 'user', 'pass');
    mysql_select_db('test', $link);

    // Make SELECT query
    $data = mysql_fetch_array(mysql_query("SELECT `file`, `mime` FROM `files` WHERE `id` = '{$id}'", $link), MYSQL_ASSOC);

    // Set the content type header
    header('Content-type: '.$data['mime']);

    // Also notice that I am not stripping the slashes, 
    // Doing so may corrupt data in certain file types, 
    // while you may need to do so for others.
    echo $data['file'];
?>
Also have a look at:
http://www.php.net/manual/en/feature...ad.post-method

Which explains the $_FILES superglobal and the information available in it.

The 'file' link may also be included in the 'src' attribute of an <img> tag.

: )
Rich

:::::::::::::::::::::::::::::::::
Smiling Souls
http://www.smilingsouls.net
:::::::::::::::::::::::::::::::::
  #7 (permalink)  
Old February 14th, 2004, 07:55 PM
Authorized User
 
Join Date: Sep 2003
Location: , , .
Posts: 18
Thanks: 0
Thanked 0 Times in 0 Posts
Default

thank you..but..this is the cose that i used to visualizing the image (excuse me for my english:-))

<?php
    //dopo l'inserimento dell'immagine, controllo che l'id sia stato passato correttamente.
    if (isset($_GET['ID']))
    {
        $id = $_GET['ID'];
    }

    //quindi mi collego al database
    $collegamento = mysql_connect('localhost', 'joe', 'joe');
    mysql_select_db('santadi', $collegamento);

    //ora creo la query
    $risultati = mysql_query("SELECT DatiBinari FROM filebinari", $collegamento);
    $data = mysql_fetch_assoc ($risultati);
    echo "<table border=1>";
    echo "<tr><td>";
    echo "<img src=\"" . $data ['DatiBinari'] . "\">";
    echo "</td></tr>";
    echo "</table>";
    ?>

When i insert $data ['DatiBinari'] inside a table..e result is this:

ÓIÁõ#ædGxpdÜš³ÌºW7/ËmÅP ¥*ß壃ɬw[zہ¿2Ì;|•DóBŽ%![ TÔŠ ô8±j‰užýi¿ÄLëDÄMŠ¿ÀòïNŠõh•Ë © ã]ô•HÉ¥Zi¹œ°¯_ìrtí   ¡Î4ò‘]z¥¦Õ:»¡sÿhf.d1à™gÃÓ)EŠÔ] ;»O‹CàªÊ#ƒ‘ç2›ˆü5Ym–â.1夬 ]G^'čª>;êj¢n(’[bÞ¯°Y³_",Eä†òª GºÉ¦ŽC¸a’ñ[‹2oY»âÄ©¸1ø)MµÇp ÊÈéµ8/4DâT%ºø¬švs™‰†ئ=}°Q¯•ÀÈu >ñ¶•I m–Uó²÷¼†ÃƒŸÉ`­(\‡Ó>:ù‡4‘N sóÑÉ29¶Õ T›lœjÁXð¦ ×"´E,O¿<@qÕ^JEB*MzmJi´!àÍXp²ˆܲ7uË ýK®­À€”Ô7!?eôÑBXÛ~f¬Èv‹DØ©Ëï ÏÛ-stÆ¡RÈ).‡… q®ßŠ›i­(0©ívmîûvì_ jÙ„¡%ïlÉõ©%KR’¦Kuc¹qDj)!xQ© & T6‚p3Ðû ›—ùËúõþÇ'@ÚZZÅÄ•søl€<¸…, '‰µÐoÜ{T7íqÞTTª[’‚ÿTRA%*? «ÿ¾V6m¥°?w&û Û°±$±=r‡¨–! Ò•WÀUCÿmIÁ‘EÌݸdØþ7e³#¾‘_ˆ•5 E9´¥*<«¯JíÐàÉâ¤S[ýŠU›/µIm=Ád!+Ä.sÖ¦œaÕòZ j¡¹¨ßþ’S¦Qô$ôÙó¶ß`b™oXU³ Éî A±]¤»æŒP E (<Éâ´×`£M 0àK¬2¸…úÙt‚кOu ¶<_j„•¡4­yFçjécZîQ®æ|ým·DŸ #Q”>¾V°”•%Æ@ó•«p’Jõ2’&¤ ....ecc...ecc.

Can you help me?

  #8 (permalink)  
Old February 14th, 2004, 08:49 PM
richard.york's Avatar
Wrox Author
Points: 5,506, Level: 31
Points: 5,506, Level: 31 Points: 5,506, Level: 31 Points: 5,506, Level: 31
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Jun 2003
Location: Camby, IN, USA.
Posts: 1,706
Thanks: 0
Thanked 6 Times in 6 Posts
Default

Quote:
quote:Originally posted by joeore
    echo "<img src=\"" . $data ['DatiBinari'] . "\">";
Well you aren't supposed to dump the binary data into the <img> tag. You must refer to an external php script via the img tag to get the browser to display the image.

$risultati = mysql_query("SELECT ID FROM filebinari", $collegamento);
$data = mysql_fetch_assoc ($risultati);

Where is your WHERE clause?? Are you selecting *all* of the rows in the database? Select the unique ID and pass it to another, a second, PHP script to output the image. This is the same as you would use to reference a .jpg or .gif.. file. The PHP script essentially mimicks everything neccessary for the image to be displayed. I suggest you have another look at my last example. In the second script, you must make a content-type header change for the images's MIME type, such as, image/jpeg, image/x-png, image/gif, etc.. whichever one corresponds to your image type being used. This header change will tell the browser that the content coming along is an image and trigger it to process it as one.

If you use my original script as is, you need only modify this line to the following... and the query above to SELECT the ID field instead of the binary data...

echo "<img src='viewdbfile.php?ID={$data['ID']}' />";

hth,
Rich


:::::::::::::::::::::::::::::::::
Smiling Souls
http://www.smilingsouls.net
:::::::::::::::::::::::::::::::::
  #9 (permalink)  
Old February 14th, 2004, 09:22 PM
Authorized User
 
Join Date: Sep 2003
Location: , , .
Posts: 18
Thanks: 0
Thanked 0 Times in 0 Posts
Default

excuse me..:-(((--but i don't understand well :-( can you help me with an example?...

  #10 (permalink)  
Old February 15th, 2004, 05:51 PM
richard.york's Avatar
Wrox Author
Points: 5,506, Level: 31
Points: 5,506, Level: 31 Points: 5,506, Level: 31 Points: 5,506, Level: 31
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Jun 2003
Location: Camby, IN, USA.
Posts: 1,706
Thanks: 0
Thanked 6 Times in 6 Posts
Default

Look at my original example again, this time modify the following line:
echo "Upload successful! <a href='viewdbfile.php?id=".mysql_insert_id()."'>Cli ck here to view the file!</a>\n";

To say the following:
echo "Upload successful!<br />Image inserted:<br /><img src='viewdbfile.php?id=".mysql_insert_id()."' style='border: 1px solid black; margin: 10px;' />";

The mysql_insert_id() refers to the unique ID just assigned to the field, in this case an auto-incrementing integer. Without the ID you would not be able to distinguish one image from another.

If that doesn't make sense to you then I suggest you explain what doesn't make sense about it.

: )
Rich

:::::::::::::::::::::::::::::::::
Smiling Souls
http://www.smilingsouls.net
:::::::::::::::::::::::::::::::::


Similar Threads
Thread Thread Starter Forum Replies Last Post
Upload Multiple Files Anypond .NET Framework 2.0 1 February 21st, 2008 05:07 AM
cant upload files akber ASP.NET 1.0 and 1.1 Basics 3 November 6th, 2006 03:06 AM
UPLOAD - MULTIPLE - FILES cli PHP How-To 5 May 29th, 2005 04:59 PM





Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
Copyright (c) 2020 John Wiley & Sons, Inc.