2

i have to save the files from input fields to database,i'll do it this way:

    $mkey = mysqli_insert_id($mysqli);
    $i=0;
    while (isset($_FILES['file'.$i])) {
        $filepath = ini_get('upload_tmp_dir')."/".basename($_FILES['file'.$i]['tmp_name']);
        $filepath = addslashes($filepath);
        $handle = fopen($filepath, "rb");
        $content = fread($handle, filesize($filepath));
        $stmt = $mysqli->prepare("INSERT INTO attachment (filename,filecontent,mkey) VALUES (?,?,?)");
        $stmt->bind_param("sbi",$_FILES['file'.$i]['name'],$content,$mkey);
        $stmt->execute();
        fclose($handle);
        $i++;
    }

no error occured,and the other 2 fields mkey and filename are filled in database columns,but the content no,$content shown with print_r in my browser and i sure the $content variable is not empty,but mysql shows me nothing of the content.

Francesco
  • 69
  • 3
  • 10
  • 1
    It's probably not a good idea trying to store binary files in SQL; if you do decide that's what you want to do, then you should at least convert the data to hex first. – l'L'l Dec 25 '14 at 00:03
  • @l'L'l definitely not a good idea,but i've to deal with this in this case. converting to hex?!and when i want to load it back convert it again?? – Francesco Dec 25 '14 at 00:07
  • 1
    read about [mysqli_stmt_send_long_data](http://php.net/manual/en/mysqli-stmt.send-long-data.php) this should be used to store binary files into database, also - you don't have any error checking in your code... – Iłya Bursov Dec 25 '14 at 00:10
  • Look at `bin2hex()` and then when you want to load it back use `hex2bin()`. Here's something similar that might help: http://stackoverflow.com/a/5534337/499581. Lashane's suggestion will work too, but for images they need to be `utf8_encoded` first. – l'L'l Dec 25 '14 at 00:10

1 Answers1

2

RTM ;-)

If data size of a variable exceeds max. allowed packet size (max_allowed_packet), you have to specify b in types and use mysqli_stmt_send_long_data() to send the data in packets.

So I have never done this myself but i would assume it needs to look something like this based on your code and the example on the functions doc page:

    $filepath = ini_get('upload_tmp_dir')."/".basename($_FILES['file'.$i]['tmp_name']);
    $filepath = addslashes($filepath);
    $handle = fopen($filepath, "rb");
    $content = null;

    $stmt = $mysqli->prepare("INSERT INTO attachment (filename,filecontent,mkey) VALUES (?,?,?)");
    $stmt->bind_param("sbi",$_FILES['file'.$i]['name'], $content, $mkey);

    while (!feof($handle)) {
        // $maxPacketSize would be the size of your max packet setting for mysql,
        // or something safely assumed to be below it
        $stmt->send_long_data(1, fread($handle, $maxPacketSize));
    }
    fclose($handle);
    $stmt->execute();
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
prodigitalson
  • 60,050
  • 10
  • 100
  • 114