Hi, wondering if somebody can tell me where I'm going wrong (I'm new to all of this). I have the following php code which uploads an image file into my database:

    //Connect to database
    include 'Resources/Include/db.inc.php';

    //get users IP

    //Don't do anything if file wasn't selected
    if (!empty($tmp)) {

    //Copy file to temporary folder
    copy($tmp, "./temporary/".$ip."");

    //open the copied image, ready to encode into text to go into the database
    $filename1 = "./temporary/".$ip;
    $fp1 = fopen($filename1, "rb");

    //record the image contents into a variable
    $contents1 = fread($fp1, filesize($filename1));

    $contents1 = addslashes($contents1);

    //close the file

    $ftype = $_FILES['image']['type'];

    //insert information into the database
    if(!mysql_query("INSERT INTO LetterImages (Data,Type,LetterID,Page)"." VALUES ( '$contents1', '$ftype',1,1)")){
    echo mysql_error();

    //delete the temporary file we made


This seems to work ok, as when I go to the LetterImages table there is now an additional row with a file in the blob field. I then have the following code which is supposed to display the image:

   $result=mysql_query("SELECT * FROM LetterImages WHERE LetterID=1 AND Page=1");

    //fetch data from database


    //tell the browser what type of image to display
    header("Content-type: $ftype");

    //decode and echo the image data
    echo $encoded;

Instead of displaying an image, however, this just displays pages and pages of incomprehensible data. Can anybody tell me where I'm going horribly wrong?