BLOB数据写入数据库失败

541*_*35d 4 php mysql mysqli blob

我创建了一个数据库,用于存储有关图像以及图像本身的各种数据。我有五把钥匙(id, name, size, format, file)。是id自动递增的。是fileBLOB 类型的值 - (mediumblob)。休息有其各自的类型。奇怪的是,除了 BLOB 图像本身之外,所有其他变量都已成功写入数据库。

等待用户使用以下命令上传图像$_POST:

if(isset($_POST['file_one_submit'])){
    $post = 'file_one_input';
}
Run Code Online (Sandbox Code Playgroud)

定义所有变量。包括$file变量:

$file = file_get_contents($_FILES[$post]['tmp_name']);
Run Code Online (Sandbox Code Playgroud)

然后我进行查询以用新信息替换数据库中的记录:

$stmt = $conn -> prepare("REPLACE INTO `images` (id, name, size, format, file) VALUES(?, ?, ?, ?, ?);");
$stmt -> bind_param("isisb", $id, $name, $size, $format, $file);
$stmt -> execute();
Run Code Online (Sandbox Code Playgroud)

file执行查询后,数据库中的所有记录都会成功更新,但应包含 BLOB 数据的列除外。我认为该$post变量可能定义不正确,但获取上传文件的名称例如可以:

upload_name = $_FILES[$post]['name'];
Run Code Online (Sandbox Code Playgroud)

我尝试回显该$file变量以检查其内容,但收到了一大堆垃圾数据,我认为这些数据是在使用该file_get_contents()函数转换为 BLOB 期间生成的正确字符串。

我已经检查过文件的大小没有超出mediumblobBLOB 类型的容量。我还尝试通过这篇文章检查我的代码中的错误,但没有成功。代码运行时页面上不会出现任何错误或警告。我还启用了错误/警告检查,E_STRICT但仍然没有输出。

Dou*_*uma 5

我通过使用方法让它工作send_long_data。(在这些示例中,我删除了一些与示例无关的列)。

选项 1:使用 send_long_data 方法传递二进制数据

b根据https://www.php.net/manual/en/mysqli-stmt.bind-param.php使用的好处:

笔记:

如果变量的数据大小超过最大值。允许的数据包大小(max_allowed_pa​​cket),您必须在类型中指定 b 并使用 mysqli_stmt_send_long_data() 以数据包形式发送数据。

//...

if(isset($_POST['file_one_submit'])){
    $post = 'file_one_input';

    $id = 1;
    $file = NULL;

    $stmt = $conn -> prepare("REPLACE INTO `images` (id, file) VALUES(?, ?);");
    $stmt->bind_param("ib", $id, $file);
    
    //send_long_data(int $param_num, string $data): bool
    $stmt->send_long_data(1, file_get_contents($_FILES[$post]['tmp_name'])); 
    $stmt->execute();
}
?>

<form action="file.php" method="post" enctype="multipart/form-data">
    <input type="file" name="file_one_input" />
    <input type="submit" name="file_one_submit" value="Upload" />
</form>
Run Code Online (Sandbox Code Playgroud)

选项 2:将 b 更改为 s

我认为使用 b 更好,但如果我将 b 更改为 s (字符串),这似乎也有效:

//...

if(isset($_POST['file_one_submit'])){
    $post = 'file_one_input';

    $id = 1;
    $file = file_get_contents($_FILES[$post]['tmp_name']);

    $stmt = $conn -> prepare("REPLACE INTO `images` (id, file) VALUES(?, ?);");
    $stmt->bind_param("is", $id, $file);
    $stmt->execute();
}
?>

<form action="file.php" method="post" enctype="multipart/form-data">
    <input type="file" name="file_one_input" />
    <input type="submit" name="file_one_submit" value="Upload" />
</form>
Run Code Online (Sandbox Code Playgroud)