php - 二进制文件内容显示在php print_r中但未保存在mysql中

标签 php mysql file-upload mysqli

我必须将文件从输入字段保存到数据库,我会这样做:

    $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++;
    }

没有发生错误,其他2个字段mkey和文件名填充在数据库列中,但内容没有,$content在我的浏览器中用print_r显示,我确定$content变量不为空,但mysql没有显示任何内容内容。

最佳答案

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.

所以我自己从来没有这样做过,但我认为根据您的代码和 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();

关于php - 二进制文件内容显示在php print_r中但未保存在mysql中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27643175/

相关文章:

php - 查询3个表的数据

php - PHP数组与数据库的性能

python - MySQLdb connection.py "cant connect"与 Django

javascript - 上传 100% 完成到 rackspace 云存储后,Blueimp jquery 文件上传插件抛出错误

javascript - 在 jQuery BlueImp uploader 中删除文件名中的空格

php - 如何将闭包绑定(bind)到 PHP 中的静态类变量?

php - 选择表格分页时不会转到不同的页面

php - 如何使用数据库字段调用 PHP 文件?

php - 尝试在 Yii2 中加载双列表框时出错

node.js - 如何使用 ExpressJS/Connect/Crypto 获取(大)文件的校验和?