Adding a file to SQL and retrieving it.

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Anarking
Forum Newbie
Posts: 24
Joined: Wed Feb 11, 2009 11:29 am

Adding a file to SQL and retrieving it.

Post by Anarking »

Hi there,

I was trying to get this code to work that I found. I want to insert a file into my MySQL and download it again later. It all inserts well enough but when it comes to downloading, it wont save as a file, it just opens in the window im using.

This is ok for things like text files but other file ill need to save.

Any tips how ill finish off the last part?

Thanks


Heres the code I used, it was from here

http://php.about.com/od/phpbasics/ss/mysql_files_6.htm

Code: Select all

<form method="post" action="upload.php" enctype="multipart/form-data">
Description:<br>
<input type="text" name="form_description" size="40">
<input type="hidden" name="MAX_FILE_SIZE" value="1000000">
<br>File to upload:<br>
<input type="file" name="form_data" size="40">
<p><input type="submit" name="submit" value="submit">
</form>

Code: Select all

<?php
mysql_connect("localhost","root","root");
mysql_select_db("testing");
$data = addslashes(fread(fopen($form_data, "r"), filesize($form_data)));
$result=MYSQL_QUERY("INSERT INTO uploads (description, data,filename,filesize,filetype) ". "VALUES ('$form_description','$data','$form_data_name','$form_data_size','$form_data_type')");
$id= mysql_insert_id();
print "<p>File ID: <b>$id</b><br>";
print "<p>File Name: <b>$form_data_name</b><br>";
print "<p>File Size: <b>$form_data_size</b><br>";
print "<p>File Type: <b>$form_data_type</b><p>";
print "To upload another file <a href=http://www.yoursite.com/yourpage.html> Click Here</a>";
?>

Code: Select all

<?php
mysql_connect("localhost","root","root");
mysql_select_db("testing");
$query = "SELECT data,filetype FROM uploads where id=$id";
$result = MYSQL_QUERY($query);
$data = MYSQL_RESULT($result,0,"data");
$type = MYSQL_RESULT($result,0,"filetype");
Header( "Content-type: $type");
print $data;
?>
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Adding a file to SQL and retrieving it.

Post by requinix »

Take a look at the manual page for header. One of the examples shows how to do a file download.
Post Reply