How can I insert file from POST into longblob column using PHP 7 and MySQL?

蹲街弑〆低调 提交于 2019-12-25 04:16:07

问题


I'm using PHP 7 and MariaDB 5.5.47 (on CentOS 7) and the following code successfully executes, with no errors:

$id = 3;
$tmp_name = $_FILES['file']['tmp_name'];
$fp = fopen($tmp_name, 'rb');

$statement = $db->prepare("INSERT INTO Foo (id, data) VALUES (?, ?)");
$statement->bindParam(1, $id);
$statement->bindParam(2, $fp, PDO::PARAM_LOB);
$statement->execute();
$statement->closeCursor();
close($fp);

Using MySQL WorkBench it shows the "data" column is "BLOB" (as opposed to null, in the event I insert nothing). When I try to query the data, it's zero bytes. This code worked with PHP 5, but I haven't found any reason why it wouldn't work with PHP 7.


回答1:


Switching to reading the content and passing that in worked.

$fp = fopen($tmp_name, 'rb');
$content = fread($fp, filesize($tmp_name));
// ...
$statement->bindParam(2, $content, PDO::PARAM_LOB, $size);

However, I run into errors about memory when uploading a file that's > 20mb:

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 81606320 bytes) in /var/www/app/API/docs.php on line 498




回答2:


Use the PHP way of increasing its memory usage:

ini_set('memory_limit', '210M');

Notice that it already had 128M allocated, and it was trying to allocate 80M more -- is that the size of the file?

Adjust the value in init_set as needed. BUT... If MySQL is on the same server, then you should tune it downward. innodb_buffer_pool_size is the likely one to tweak.

Keep in mind that swapping is terrible for performance.



来源:https://stackoverflow.com/questions/40053736/how-can-i-insert-file-from-post-into-longblob-column-using-php-7-and-mysql

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