1. Computing

Storing User Submitted Data and Files in MySQL

By , About.com Guide

6 of 7

Retrieving Files
We already learned how to retrieve plain data from our MySQL database. Likewise, storing your files in a MySQL database wouldn't be very practical if there wasn't a way to retrieve them. The way we are going to learn to do this is by assigning each file a URL based on their ID number. If you will recall when we uploaded the files we automatically assigned each of the files an ID number. We will use that here when we call the files back. Save this code as download.php

<?php 
 mysql_connect("your.server.com","username","password"); 
 mysql_select_db("database_name"); 
 $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; 
 ?> 

Now to retrieve our file, we point our browser to: http://www.yoursite.com/download.php?id=2 (replace the 2 with whatever file ID you want to download/display)

This code is the base for doing a lot of things. With this as a base you can add in a database query that would list files, and put them in a drop down menu for people to choose. Or you could set ID to be a randomly created number so that a different graphic from your database is randomly displayed each time a person visits. The possibilities are endless.

Related Video
Zip File 101
Share a File or Folder in Vista
  1. About.com
  2. Computing
  3. PHP / MySQL
  4. PHP with MySQL
  5. Retrieving file uploads to MySQL

©2013 About.com. All rights reserved.