Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations sizbut on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Uploading images to mysql with php - issues

Status
Not open for further replies.

imryn

Programmer
Dec 2, 2002
75
US
hello everyone,

I can't seem to find out what is wrong with my code here. It won't upload to the database, and I am not sure why either. Can anyone help. When I run the code this way all I get is the form view back after is appears to do something. If I do something like

// Declaration
$okay = $_POST['action'];

and substitute it for the if($okay == "update")

then all I get is a white... blank... browser to stare at
does anyone have an idea, what I did wrong?



<?php
error_reporting(E_ALL);

if ($action == "upload") {

include "open_db.inc";

if (isset($binFile) && $binFile != "none") {
$data = addslashes(fread(fopen($binFile, "r"), filesize($binFile)));
$strDescription = addslashes($txtDescription));
$sql = "INSERT INTO binary_data";
$sql .= "(description, bin_data, filename, filesize, filetype) ";
$sql .= "VALUES ('$strDescription', '$data', ";
$sql .= "'$binFile_name', '$binFile_size', '$binFile_type')";
$result = mysql_query($sql, $db);
mysql_free_result($result);
echo "Thank you. The new file was successfully added to our database.<br><br>";
echo "<a href='main.php'>Continue</a>";
}
mysql_close();

} else {
?>
<HTML>
<BODY>
<FORM METHOD="post" ACTION="add2.php" ENCTYPE="multipart/form-data">
<INPUT TYPE="hidden" NAME="MAX_FILE_SIZE" VALUE="90000000">
<INPUT TYPE="hidden" NAME="action" VALUE="upload">
<TABLE BORDER="1">
<TR>
<TD>Description: </TD>
<TD><TEXTAREA NAME="txtDescription" ROWS="10" COLS="50"></TEXTAREA></TD>
</TR>
<TR>
<TD>File: </TD>
<TD><INPUT TYPE="file" NAME="binFile"></TD>
</TR>
<TR>
<TD COLSPAN="2"><INPUT TYPE="submit" VALUE="Upload"></TD>
</TR>
</TABLE>
</FORM>
</BODY>
</HTML>
<?php
}
?>


imryn
 
I didn't go over the whole code, but thought I'd throw in a suggestion that I know I can easily help with if you're interested.

I do a similar thing, but I don't upload the picture to a database, and I don't suggest doing that. I suggest uploading the pictures to a certain folder, and giving the address of that image into the database

-Kerry
 
Hello Kerry,

Okay, you have my attention, I am interested into learning more about this giving the address of that image into the database. Can you elaborate on this somemore?
 
Yeah sure.

Basically the theory is that if you have the address of the images (which you upload first), then when you call the database and ask for the pictures you simply put it in as the source, and it links to the picture. This means you don't have to bother about putting images or files into a database, simply text like "../images" or whatever it may be.

Here's two pages that I use to do the work for me.

upload.htm
Code:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"></head>
<body text="#ffffff" vlink="#ffffff" alink="#ffffff" link="#ffffff" bgcolor="#0000cc">
    <h2 align="center"><font size="7"><strong>Upload Picture</strong></font> 
    </h2>
	<center><font size ="5"><a href="index.html">Click here to return to main page.</a></font></center>
    <p align="left">
    </p>
    <p align="left">
        <font size="4">Click the "Browse" button to search for a picture on your computer.
        &nbsp; 
        <br />
        Once you have selected the file, click the"Open" button to put the file in the box
        below.<br>
		You do not have to upload a member picture and logo picture, all combinations work.</font> 
    </p>
[blue]    <form action="myupload.php" method="post" enctype="multipart/form-data"> [/blue]
        <p>
        &nbsp;<input [red]type="file"[/red] [green]name="userfile"[/green] /><font><strong>Member Picture</strong></font>
        </p>
		<p>
            &nbsp;<input [red]type="file" [/red][green]name="logofile"[/green] /><font><strong>Logo Picture</strong></font>
        </p>
        <p align="left">
            <br />
            <font size="4">Now click the "Submit Picture" button to put your picture on the website.</font> 
        </p>
        <p>
            <input type="submit" value="Submit Query"/>
            <br />
        </p>
    </form>
</body>
</html>

myupload.php
Code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Upload Images</title>
<?
[blue]
if(!empty([/blue][green]$_FILES["userfile"][/green][blue])) {
    [red]$uploaddir = "../../mempics/";[/red] 
    if (move_uploaded_file([/blue][green]$_FILES["userfile"][/green][blue]["tmp_name"], $uploaddir . [/blue][green]$_FILES["userfile"][/green][blue]["name"])) [/blue]{
	print '
	<h2 align="center"><font size="6"><strong><em>Member picture has been successfully uploaded!
	</em></strong></font> </h2>	';
    } else {
	print '
	<h2 align="center"><font size="6"><strong><em>No member picture uploaded. If this is an error, contact your website builder/maintainer.</em></strong></font> </h2>
	';
    }
}
[blue]
if(!empty([/blue][green]$_FILES["logofile"][/green][blue])) {
    [/blue][red]$uploaddir = "../../logos/";[/red][blue] 
    if (move_uploaded_file([/blue][green]$_FILES["logofile"][/green][blue]["tmp_name"], $uploaddir . [/blue][green]$_FILES["logofile"][/green][blue]["name"])) [/blue]{
	print '
	<h2 align="center"><font size="6"><strong><em>Logo picture has been successfully uploaded!
	</em></strong></font> </h2>
	';
    } else {
	print '
	<h2 align="center"><font size="6"><strong><em>No logo uploaded. If this is an error, contact your website builder/maintainer.</em></strong></font> </h2>
	';
    }
}
?>
</head>
<body text="#ffffff" vlink="#ffffff" alink="#ffffff" link="#ffffff" bgcolor="#0000cc">
<p align="center"><a href="upload.htm">
	<font size="5">Upload Another Picture</font></a></p><div align="center"><div align="center">
	<p> <a style="FONT-SIZE: 14pt" href="index.php"><font size=5>Back To Main Page</font>
	</a></p></div>
</body>
</html>

to access the picture, its like this:
Code:
<img src="mempics/<? echo $rows[2] ?>" width="150" height="200" border="0">

where it was a member (thats why its in mempics) and I retrieved an array of all the fields of a person, and rows[2] was the field that I inserted the file name into, and I literally just inserted the file name:

Code:
$strSql .= " '" . $_FILES["photo"]["name"] . "',";
$strSql .= " '" . $_FILES["logo"]["name"] . "',";

Note thats in the middle of my SQL statement that I make when I'm declaring the values, but I just inserted the filename.

Note that if you are going to allow any user to do this you need to put in some validation, this is behind a password and the owner of the site does it. This uploads two images, one for a logo one for a membership pic.

Hope this was useful,
Kerry
 
imryn

you are referencing the file as $binFile (and other variables similarly). this makes me wonder whether you have register globals switched on. bad idea.

the file element on your form is called binFile and the data that the browser provides on the uploaded file will be in the $_FILES['binFile'] element of the $_FILES superglobal.

Code:
<?

if (isset($_FILES['binFile'])):
	If ($_FILES['binFile']['error'] == "UPLOAD_ERR_OK"):
		$binFile = $_FILES['binFile']['tmp_name'];
		$data = mysql_escape_string(file_get_contents($binFile));
		
		if (!get_magic_quotes_gpc):
			$strDescription = mysql_escape_string($_POST['txtDescription']);
		endif;
		$sql = "INSERT INTO binary_data";
		$sql .= "(description, bin_data, filename, filesize, filetype) ";
		$sql .= "VALUES ('$strDescription', '$data', ";
		$sql .= "'".basename($_FILES['binFile']['name'])."', '{$_FILES['binFile']['size']}', '{$_FILES['binFile']['type']})";
		$result = mysql_query($sql, $db);
		if ($result):
			echo "Thank you. The new file was successfully added to our database.<br><br>";
			echo "<a href='main.php'>Continue</a>";
		else:
			echo "There was a problem saving your file to the database ".mysql_error();
		endif;
		mysql_free_result($result);
	else:
		echo "No file uploaded.  Error was ".$_FILES['binFile']['error'];
	endif;
else:
	echo "The form has not been submitted yet";
endif;

?>
 
Okay Folks,

I have revamped the code... Here is my latest issue if anyone can help me... I can upload all the data about the image EXCEPT for the image its self. I don't know why either. I have in my database columns for id, description, bin_data (longblob) , filename, filesize, filetype. every thing is in there, BUT bin_data. Where did I go wrong? Here is the new code too.

Code:
<?php
error_reporting(E_ALL);
include "open_db.inc";

if($_POST['action'] == "upload")
{
$binName = $_FILES['binFile']['name'];
$binTemp = $_FILES['binFile']['tmp_name'];
$binType = $_FILES['binFile']['type'];
$binSize = $_FILES['binFile']['size'];
$binErr = $_FILES['binFile']['error'];

if(isset($_FILES['binFile']['name'] && $_FILES['binFile']['name'] != "")
{
$data1 = fopen($binName,'rb');
$Content = fread($data1,$binSize);
$Content = addslashes($Content);
$binName = addslashes($binName);

$strDescription = addslashes($_POST['txtDescription']);

$sql = "INSERT INTO binary_data";
$sql .="(description,bin_data,filename,filesize,filetype)";
$sql .="VALUES('$strDescription','$Content','$binName','$binSize','$binType')";

$result = mysql_query($sql,$db);

echo "Thank you. The new image was successfully added to our database.<br><br>";
echo "<a href='main.php>Continue</a>

echo "<br><br><img src=".$Content."\n>";
}
else
{
print "Either isset is false or binFile is empty";
print $binErr;
}
mysql_close();
}
else
{
?>

<html>
<body>
<form method="post" action="add2.php" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="90000000">
<input type="hidden" name="action" value="upload">
<table border="1";
<tr>
<td>Description:</td>
<td><textarea name="txtDescription" rows="10" cols="50"></textaarea></td>
</tr>
<tr>
<td>File: </td>
<td><input type="file" name="binFile"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Upload"></td>
</tr>
</table>
</form>
</body>
</html>

<?php
}
?>

Thanks,
imryn
 
change this line
Code:
$data1 = fopen($binName,'rb');
to
Code:
$data1 = fopen($binTemp,'rb');
the $_FILE['element']['name'] is simply the name of the file before it was uploaded. it is not the name on the server file system which is contained in the tmp_name element.

i would also change these lines
Code:
   $data1 = fopen($binName,'rb');
   $Content = fread($data1,$binSize);
   $Content = addslashes($Content);
to
Code:
$Content = mysql_escape_string(file_get_contents($binTemp));

from file_get_contents() is the preferred way to read the contents of a file into a string. It will use memory mapping techniques if supported by your OS to enhance performance.
 
Heloo jpadie,

i am very thankful for your thoughts and ideas. I made the changes you said, and now I have a fatal error message.

Fatal error: Allowed memory size of 8388608 bytes exhausted (tried to allocate 2176515 bytes) in ...
on line 51.

Line 51 happens to be the sql statament as follows:

$sql .="VALUES('$strDescription','$Content','$binName','$binSize','$binType')";

Do you know what can be causing this error. I set in the form mega room in max size.

<input type="hidden" name="MAX_FILE_SIZE" value="90000000">

Please let me know your thoughts.

Ryan
 
jpadie,

I am just hacking away on this code and notice if I change the fopen($binTemp,'rb') to 'wb' instead I do not get that fatal error message. However, I still do not have anything in my database column bin_data which is a longblob that seems to be containing an image.

Ryan
 
Okay, so maybe I am lost... :) ... I am getting the Fatal Error message when ever I use the file_get_contents . However, I decided, that since it's a picture maybe I do not need to read it or open the file because it's a jpeg. So I tried two things
First:
$Content = mysql_escape_string($binTemp);

Second:
$Content = mysql_real_escape_string($binTemp);

now in may database in the bin_data column I have something like /tmp/phpAKodQT and /tmp/phpU1TqsE. I don't know if this really means anything, because when I attempt to display it, I get a little black and white X , as if the image is broke.... and ideas? Is it possible I got the image in the database? I will post my php code to display the image on Monday Evening EST, when I come back ... Happy Easter to everyone too...

Ryan
 
Okay, I found out what the fatal error meant, it can easily be correct by entering this line of code into your php script at the very top.

Code:

ini_set("memory_limit","12M");

or in php.ini add this

memory_limit = 12M

I am also print the image out in html once it has succesfully upload to the database, and this time it is all in unread charaters, is there a way to fix this, if so does anyone know how?

Ryan
 
hi there

a few things:
I have something like /tmp/phpAKodQT and /tmp/phpU1TqsE
these are php temporary files. where your uploads are stored. they are deleted when the script ends. to move the files to a permanent storage use move_uploaded_file().

you are getting them directly into the db as you are just inserting the file name. you need to upload the file contents
Code:
$Contents = mysql_escape_string(file_get_contents($binTemp));

it is all in unread charaters

do you mean that it does not display as an image? if so i'd guess that somewhere along the line the character set got messed up.

ensure that magic quotes is turned off everywhere.
to display the image make sure that you set the right headers before initiating the download in your fetch script (assuming an image id = 1:
Code:
set_magic_quotes_runtime(0); //otherwise the db data gets escaped unless MQR is switched off in php.ini (default)
ini_set("memory_limit","12M");
$row = mysql_fetch_assoc(mysql_query("Select bin_data, filename, filesize as len from binary_data where id='1'"));
extract($row);
header("Content-Type: "image/jpg");
header("Content-Disposition: inline; filename=$filename;";
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".$len);
echo $bin_data;
exit;
 
Hi ryan

can you try this code?

note that the code is not producing true thumbnails. we can do that later if this stage works for you.

i have not tested it for anything other than parse errors. but it should work...

note that the required db structure is in the comment block at the top of the file.

note also that i really do not recommend storing images in a database. store them in a filesystem and store a pointer in the database. nevertheless this code does db storage for you.

Code:
<?
//now check for a download request
mysql_connect("", "", "") or die(mysql_error()); //insert your details
mysql_select_db("") or die(mysql_error());// insert your details
$table = "" // table name that files are stored in
set_magic_quotes_runtime(0);
$maxsize = return_bytes(ini_get("upload_max_filesize"));
function return_bytes($val) {
   $val = trim($val);
   $last = strtolower($val{strlen($val)-1});
   switch($last):
       // The 'G' modifier is available since PHP 5.1.0
       case 'g':
           $val *= 1024;
       case 'm':
           $val *= 1024;
       case 'k':
           $val *= 1024;
   endswitch;
	return $val;
}

/*
must have a structure like this

fileid numeric auto_increment
filename varchar(255)
filetype varchar(255)
filesize varchar(15)
contents longblob
*/
$action = isset($_GET['action']) ? trim($_GET['action']) : "default";
	switch ($action):
		case "download":
			if (isset($_GET['fileid'])):
				$fileid = mysql_escape_string(trim($_GET['fileid']));
				$result = mysql_query("Select * from $table where fileid='$fileid'") or die(mysql_error());
				if (mysql_num_rows($result) !== 1):
					echo "<br/>Error downloading file";
				else:
					$row = mysql_fetch_assoc($result);
					header("Content-Type: {$row['filetype']}");
					header("Content-Disposition: attachment; filename={$row['filename']};");
					header("Content-Transfer-Encoding: binary");
					header("Content-Length: {$row['filesize']}");
					echo $row['contents'];
				endif;
			else:
				//do nothing
			endif;
		break;
		case "view":
			if (isset($_GET['fileid'])):
				$fileid = mysql_escape_string(trim($_GET['fileid']));
				$result = mysql_query("Select * from $table where fileid='$fileid'") or die(mysql_error());
				if (mysql_num_rows($result) !== 1):
					echo "<br/>Error downloading file";
				else:
					$row = mysql_fetch_assoc($result);
					header("Content-Type: {$row['filetype']}");
					header("Content-Disposition: inline; filename={$row['filename']};");
					header("Content-Transfer-Encoding: binary");
					header("Content-Length: {$row['filesize']}");
					echo $row['contents'];
				endif;
			else:
				//do nothing
			endif;
		break;
		default:

		echo <<<C
		<form action="{$_SERVER['PHP_SELF']}" method="post" enctype="application/x-[URL unfurl="true"]www-form-urlencoded"/>[/URL]
		<input type="hidden" name="MAX_FILE_SIZE" value="$maxsize" />
		Select file for upload (max 3MB): <input type="file" name="uploadedfile" /> 
		<br/>
		<input type="submit" name="submit" value="Upload" />
		</form>
		
C;
		
		if (isset ($_POST['submit'])):
			if ($_FILES['uploadedfile']['error'] == 0):
				$filetype = mysql_escape_string($_FILES['uploadedfile']['type']);
				$size = mysql_escape_string($_FILES['uploadedfile']['size']);
				$name = mysql_escape_string($_FILES['uploadedfile']['name']);
				$contents = mysql_escape_string(file_get_contents($_FILES['uploadedfile']['tmp_name']));
				//assumes an autoincrementing primary key called fileid
				$query = "	Insert into $table 
							set
							fileid = null,
							contents = '$contents',
							filename = '$filename',
							filetype = '$filetype',
							filesize = '$size'";
		
				if (mysql_query($query)):
					echo "<br/>File uploaded and saved to the database";
				else:
					echo "<br/>There was a problem saving the file to the database<br/>".mysql_error();
				endif;
			else:
				echo "<br/>Error uploading file.  The error was {$_FILES['uploadedfile']['error']}";
			endif;
		else:
			echo "<br/>No File Uploaded";
		endif;
		
		//now list all the files uploaded
		$results = mysql_query("Select fileid, filename, filetype,filesize from $table");
		echo "<table>";
		while ($row = mysql_fetch_assoc($results)):
			echo "<tr><td>{$row['filename']}</td><td>{$row['filetype']}</td><td>{$row['filesize']}</td><td><img height=\"40\" width=\"40\" src=\"{$_SERVER['PHP_SELF']}?action=view&fileid={$row['fileid']}\" /> </td><td><a href=\"{$_SERVER['PHP_SELF']}?action=download&fileid={$row['fileid']}\">Download</a></td></tr>";
		endwhile;
		echo "</table>";
endswitch;
?>
 
Hey jpadie,

Let me first start with you are amazing! and thank you for your time. Now on to a sadder note, i copied your code and ran it, it works, but it only created a fileid, and nothing else, so I am going to hack around with it and see if I can understand what you told it to do. I am still working on the other code segment to see if I can get your suggestions to work, I am having an issue at the moment with the system not knowing what the extention is.... meaning that it prompt me to open with... editor

Ryan
 
jpadie,

Okay, so after digging through some logs, I think the reason the info isn't getting upload is do to the errors I am recieving, they are
Error Message said:
Notice: Undefined index: uploadedfile in .... on line 89
Notice: Undefined index: uploadedfile in .... on line 90
Notice: Undefined index: uploadedfile in .... on line 91
Notice: Undefined index: uploadedfile in .... on line 92
Notice: Undefined index: uploadedfile in .... on line 93

Which is the following code:
jpadie said:
if ($_FILES['uploadedfile']['error'] == 0):
$filetype = mysql_escape_string($_FILES['uploadedfile']['type']);
$size = mysql_escape_string($_FILES['uploadedfile']['size']);
$name = mysql_escape_string($_FILES['uploadedfile']['name']);
$contents = mysql_escape_string(file_get_contents($_FILES['uploadedfile']['tmp_name']));

So why is this occurring? and what is the story with this too?
echo <<<C .... C;

Ryan

 
Hi Ryan

So why is this occurring? and what is the story with this too?

echo <<<C .... C;

this is the heredoc syntax. i find it easier to use this syntax with blocks of html code. effectively i just write the html code with a syntax sensitive editor, and then surround it with the heredoc string enclosure and i don't need to worry about escaping or quotes etc. there's a load of blurb in the php manual about it.

why is this occurring ...

because i was too lazy to test the code. here is a revised bit. the changes were tiny (the real problem was in the enctype i was using for the form. it should have been multipart rather than url-encoded, there were a couple of other glitches but the code would have worked).

Code:
<?
error_reporting(E_ALL);
mysql_connect("", "", "") or die(mysql_error()); //insert your details
mysql_select_db("") or die(mysql_error());// insert your details
$table = ""; // table name that files are stored in
set_magic_quotes_runtime(0);

$maxsize = return_bytes(ini_get("upload_max_filesize"));

function return_bytes($val) {
   $val = trim($val);
   $last = strtolower($val{strlen($val)-1});
   switch($last):
       // The 'G' modifier is available since PHP 5.1.0
       case 'g':
           $val *= 1024;
       case 'm':
           $val *= 1024;
       case 'k':
           $val *= 1024;
   endswitch;
    return $val;
}

/*
must have a structure like this

fileid numeric auto_increment
filename varchar(255)
filetype varchar(255)
filesize varchar(15)
contents longblob
*/
$action = isset($_GET['action']) ? trim($_GET['action']) : "default";
    switch ($action):
        case "download":
            if (isset($_GET['fileid'])):
                $fileid = mysql_escape_string(trim($_GET['fileid']));
                $result = mysql_query("Select * from $table where fileid='$fileid'") or die(mysql_error());
                if (mysql_num_rows($result) !== 1):
                    echo "<br/>Error downloading file";
                else:
                    $row = mysql_fetch_assoc($result);
                    header("Content-Type: {$row['filetype']}");
                    header("Content-Disposition: attachment; filename={$row['filename']};");
                    header("Content-Transfer-Encoding: binary");
                    header("Content-Length: {$row['filesize']}");
                    echo $row['contents'];
                endif;
            else:
                //do nothing
            endif;
        break;
        case "view":
            if (isset($_GET['fileid'])):
                $fileid = mysql_escape_string(trim($_GET['fileid']));
                $result = mysql_query("Select * from $table where fileid='$fileid'") or die(mysql_error());
                if (mysql_num_rows($result) !== 1):
                    echo "<br/>Error downloading file";
                else:
                    $row = mysql_fetch_assoc($result);
                    header("Content-Type: {$row['filetype']}");
                    header("Content-Disposition: inline; filename={$row['filename']};");
                    header("Content-Transfer-Encoding: binary");
                    header("Content-Length: {$row['filesize']}");
                    echo $row['contents'];
                endif;
            else:
                //do nothing
            endif;
        break;
        default:
		
$intmaxsize = $maxsize/(1024*1024);
        echo <<<C
        <form action="{$_SERVER['PHP_SELF']}" method="post" enctype="multipart/form-data"/>
        <input type="hidden" name="MAX_FILE_SIZE" value="$maxsize" />
        Select file for upload (max {$intmaxsize}MB): <input type="file" name="uploadedfile" />
        <br/>
        <input type="submit" name="submit" value="Upload" />
        </form>
        
C;
        
        if (isset ($_POST['submit'])):
            if ($_FILES['uploadedfile']['error'] == 0):
                $filetype = mysql_escape_string($_FILES['uploadedfile']['type']);
                $filesize = mysql_escape_string($_FILES['uploadedfile']['size']);
                $filename = mysql_escape_string($_FILES['uploadedfile']['name']);
                $contents = mysql_escape_string(file_get_contents($_FILES['uploadedfile']['tmp_name']));
                //assumes an autoincrementing primary key called fileid
                $query = "    Insert into $table
                            set
                            fileid = null,
                            contents = '$contents',
                            filename = '$filename',
                            filetype = '$filetype',
                            filesize = '$filesize'";
        
                if (mysql_query($query)):
                    echo "<br/>File uploaded and saved to the database";
                else:
                    echo "<br/>There was a problem saving the file to the database<br/>".mysql_error();
                endif;
            else:
                echo "<br/>Error uploading file.  The error was {$_FILES['uploadedfile']['error']}";
            endif;
        else:
            echo "<br/>No File Uploaded";
        endif;
        
        //now list all the files uploaded
        $results = mysql_query("Select fileid, filename, filetype,filesize from $table");
        echo "<table border=\"1\">";
        while ($row = mysql_fetch_assoc($results)):
            echo "<tr><td>{$row['filename']}</td><td>{$row['filetype']}</td><td>{$row['filesize']}</td><td><img height=\"40\" width=\"40\" src=\"{$_SERVER['PHP_SELF']}?action=view&fileid={$row['fileid']}\" /> </td><td><a href=\"{$_SERVER['PHP_SELF']}?action=download&fileid={$row['fileid']}\">Download</a></td></tr>";
        endwhile;
        echo "</table>";
endswitch;
?>
$_FILES['uploadedfile]
 
jpadie,

YOU ARE THE GREATEST!!! :) just in case no one has told you that lately. Thank you, for your time and all of your help. It works quite well, now I just need to test it out. But I do have one image in there at the moment. So why does it seem that everyone is against puting images in a database? What can happen that is so bad? I have see a ton of people say that's not a good ideal, but I haven't heard why that is. Nor have I seen any real documentation on why one should put images in a database.

Also, I am wondering, can you point me in the right direction... I am thinking about when I pull the images from the database, and making them thumbnails, so the user can click on them and enlarge them. I figure, I need to research this idea first before attempting it. Believe it or not, I did research this "great" idea of an image in the database, you see where that got me... LOL

Thank you,
Ryan
 
reasons are multiple but essentially an rdbms is designed for holding structurally related data and a file system is designed to hold bits of unrelated data. they are optimised differently and filesystems in this day and age are less likely to do a wholesale corruption routine than a database.

also many ISPs (like mine for example) give customers only 200 MB or so of db space compared to 2GB of file system space. on its own that's quite a good reason!

on the last question, if you just need a thumbnail and never need anything else (like alternative resolutions) then create a thumbnail column in your database as a longblob and create the thumbnail at the point of upload. there is a script that i have seen recently posted in this forum or just search for php thumbnail. it's actually a very easy transformation provided you have the gd or imagemagik library loaded.

hth
Justin
 
Justin,

First, when you say
provided you have the gd or imagemagik library loaded

What do you exactly mean by that? loaded in Apache or something to do with the php.ini file? I will need to check for these options.

I am happy that i finally got an exceptible comment about why not use a database... I didn't think about the size issue with an ISP or Hosting company.... thanks for opening my eyes to that one.

And last but least, my end goal was for an alternative resolutions I am just trying to figure out what my best options are at this time. If I look at doing a alternative resolution, is that (enlarging) done in the php code or does that take up physical space. I don't care if it uses RAM either. Do you know how to check the size of your db ? and see how it grows as one inputs data into it....?

For some stupid reason, I thought that maybe keeping images in a database may reduce the amount of room on a Hard Drive I was occupping. I never thought of the size of the database. I will need to really look at this.

Ryan
 
the usual way of doing thumbnails is to have a script which searches for the thumbnail in a particular directory. if it can't find it, the script gets the original image and thumbs it, storing it in the thumbs directory for use the next time a user accesses that image or page. thus there is a basic and efficient form of cacheing going on. if at any time you start running out of host-space you can always delete all the cache and let it build up again.

the gd and imagemagic libraries are loaded by php. they are needed to manipulate images. the hosts that i use all have at least gd loaded by default. you can check this easily with a call to phpinfo()

hth
Justin
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top