Better way to insert blob into MySQL with PHP

孤街醉人 提交于 2019-12-04 05:54:09

Using the send_long_data method will allow you to solve the case where a file is too big compared to the max_allowed_packet value in your particular MySQL server setup. However the fact your two codes works demonstrate that you did not reach this limit in your tests. The send_long_data method has been designed to be called multiple times in a loop with partial "chunks" of the data too big to be send in one pass. Furthermore I do not favor the way you wrote the second code because you are not able to handle error during file read. I will suggest a third way to code this :

define ('YOUR_MYSQL_MAX_ALLOWED_PACKET', 8192);
$fp = fopen($tmpName, "r");
// TODO check here if fopen succeed
$prep_stmt = "INSERT INTO dokumenty (name, size, type, content, autor, poznamka) VALUES (?, ?, ?, ?, ?, ?)";
$stmt = $mysqli->prepare($prep_stmt);

while (!feof($fp)) {
    $stmt->send_long_data(3, fread($fp, YOUR_MYSQL_MAX_ALLOWED_PACKET));
}
fclose($fp);

Where the YOUR_MYSQL_MAX_ALLOWED_PACKET constant value must be adjusted to your MySQL particular setup.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!