3/19/09

Save binary in MySQL by PHP

2 ways to do it.

For TEXT fields (max 65535 bytes), LONGTEXT fields (max 4GBytes) you must convert to base64 in PHP

$binary_data = file_get_contents($file);
$string_data = base64_encode($binary_data
);

and save the contents to the column
$sql = "INSERT INTO table (text_field) VALUES('$string_data')";

For BLOB fields (MAx 65535 bytes) or LONGBLOB (Max 4 GB) just put the contents directly to the SQL
$sql ="INSERT INTO table (text_field) VALUES('".$binary_data ."')";

Have some issues about put binary content in a SQL statement. Sometimes, the binary contents simulate the char QUOTE.
Its better don't use mysal_query function. If you use some Abstraction Layer Like PDO or ADODB, it will escape correctly the content to prevent this kind of trouble.

NOTE FROM the MySQL manual: The maximum size of a BLOB or TEXT object is determined by its type, but the largest value you actually can transmit between the client and server is determined by the amount of available memory and the size of the communications buffers. You can change the message buffer size by changing the value of the max_allowed_packet variable, but you must do so for both the server and your client program

No comments: