<?php
error_reporting(E_ALL);
set_time_limit(3600);
mysql_connect('localhost', 'root', '');
mysql_select_db('test');
$Filename = 'A100MBFile.dat';
$sql = "INSERT INTO `bin-data` SET `Name` = 'Sample', `Size` = '".filesize($Filename)."'";
$res = mysql_query($sql) or die(mysql_error());
$id = mysql_insert_id();
$fh = fopen($Filename, "r");
while (!feof($fh))
{
$buffer = fread($fh, 1024); // 1KB
mysql_query("UPDATE `bin-data` SET `Data` = CONCAT(`Data`, '".addslashes($buffer)."') WHERE `FileID` = $id");
}
fclose($fh);
?>
Obviously, CONCAT is not good here as it returns the current data added to the buffer. Im looking for a solution that adds data using only 1KB at a time.
Does work for BLOB datatypes but Im looking for a solution that reads only 1KB for that UPDATE string.
CONCAT(`Data`, '".addslashes($buffer)."') returns (1KB + existing size of `Data`) which keeps increasing on the next UPDATE query. This is not ideal for storing huge files.
Obviously if you concatenate the data in the database with the contents of $buffer you're going to get data.$buffer. That's what the concat() function is for.
If you want to get 1kb of data.$buffer then you'll need to get the contents of data, append $buffer, chop off whatever bit you don't want, and then update the database with the new contents. There won't be a simple PHP function for it.
Or, if you're using MySQL 5 you might be able to create a stored procedure to do it .. but that would be pretty complicated.
Im not trying to retrieve data from the MySQL database, Im trying to insert a 100MB file in a LONGBLOB field by adding 1KB at a time instead of one big $data = fread(fopen($Filename, "r"), filesize($Filename)) which stores 100MB to $datastring.
while (!feof($fh))
{
$buffer = fread($fh, 1024); // 1KB
mysql_query("UPDATE `bin-data` SET `Data` = CONCAT(`Data`, '".addslashes($buffer)."') WHERE `FileID` = $id");
}
But how do I keep adding 1024 byte chunks to the current existing `Data`.
Appending 1KB to an existing 1GB file wont have the overhead of reading the 1GB file first. Open for append mode and add 1KB data to it.
I want to do the same thing for a LONGBLOB field in a mysql database.
The concat call doesn't assign the field to any other variable. There is no functionality you are thinking exists. You've already found the only manor in which this would work. Be happy.
That would depend on the optimization the database of interaction chooses. For MySQL or several other databases that would potentially involve looking at their internal code if you really want to know, definitively. I'm certainly not going to look in there for you.
The problem is, there is no alternative. You will need to use it if you continue with the implementation you've currently chosen.