Save imagepng to MySQL database

I have a script that creates an image and calls imagepng to output it to the browser. Instead, I would like to store it in a MySQL database (like blob). I know how to read a file in a prepared statement

 while ($data = fread($fp, 1024)) { $size += strlen($data); $stmt->send_long_data(0, $data); } 

The problem is that I do not want imagepng write to the file so that I can read it back to the database.
Is there an easy way to do this?

UPDATE: This is how I tried to use output buffering:

 ob_start(); imagepng($dst_r,null); $img = ob_get_clean(); $db = Database::getInstance(); // Singleton on MySQLi $s = $db->prepare("UPDATE " . $db->getTableName("Users") . " SET `Picture` = ? WHERE `UserID` = ?" ); $s->bind_param('bi', $img, $_POST['UserID']); $s->send_long_data(0, $img); $s->execute(); 

The database is not updated and there are no errors.

+4
source share
1 answer

From what I just read in php.net , you can probably do this using a combination of ob_start () , ob_get_contents and ob_end_clean () .

By measurement, I mean that:

 ob_start(); imagepng($image); $imageContent = ob_get_contents(); ob_end_clean(); 

If I were you, I would save it in a temporary file, but I do as you wish :)


Edit: I think you also have problems managing your DB. Here is what might work

 //include here the thing to get $imageContent $db = Database::getInstance(); // Singleton on MySQLi $s = $db->prepare("UPDATE " . $db->getTableName("Users") . " SET `Picture` = ? WHERE `UserID` = ?" ); $null = NULL; $s->bind_param('bi', $null, $_POST['UserID']); $byteToSend = 1024;//this should equals the max_allowed_packet variable in your mysql config (usually in my.cnf config file) $i=0; while ($contentToSend = substr($imageContent, $i, $byteToSend)) { $s->send_long_data(0, $contentToSend); $i+=$byteToSend; } 
+10
source

Source: https://habr.com/ru/post/1403355/


All Articles