Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to insert blob into MySQL with PHP

Tags:

php

mysql

blob

I am working on a system where I insert files into the database. There are two ways how I am able to insert blob into DB, so I'm curious which one is better.

The first is to get the content and then bind parameter of content as a string when inserting:

 $fp      = fopen($tmpName, 'r');
 $content = fread($fp, filesize($tmpName));
 $content = addslashes($content);
 fclose($fp);
 ...
 $prep_stmt = "INSERT INTO dokumenty (name, size, type, content, autor, poznamka) VALUES (?, ?, ?, ?, ?, ?)";
        $stmt = $mysqli->prepare($prep_stmt);
              $stmt->bind_param('sissis',$fileName,$fileSize,$fileType,$content,$user_id,$poznamka );

The other way is to use send_long_data like this:

 $content = NULL;
 ...
 $prep_stmt = "INSERT INTO dokumenty (name, size, type, content, autor, poznamka) VALUES (?, ?, ?, ?, ?, ?)";
        $stmt = $mysqli->prepare($prep_stmt);
             $stmt->bind_param('sisbis',$fileName,$fileSize,$fileType,$content,$user_id,$poznamka );
        $stmt->send_long_data(3, file_get_contents($tmpName));

My question is: which way is better to use as both works?

like image 578
Mi Ro Avatar asked Jun 29 '15 08:06

Mi Ro


1 Answers

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.

like image 65
Guillaume Pagnard Avatar answered Oct 09 '22 11:10

Guillaume Pagnard