Use prepared statements to ensure integrity of binary data during storage and retrieval. Escaping/quoting by f.e. sqlite_escape_string() or PDO::quote() is NOT suited for binary data - only for strings of text.
A simple test verifies perfect storage and retrieval with prepared statements:
<?php
$num_values = 10000;
$db = new pdo( 'sqlite::memory:' );
$db->exec( 'CREATE TABLE data (binary BLOB(512));' );
for( $i = 0; $i < $num_values; $i++ )
{
for( $val = null, $c = 0; $c < 512/16; $c++ )
$val .= md5( mt_rand(), true );
@$binary[] = $val;
}
for( $i = 0; $i < $num_values; $i++ )
$db->prepare( 'INSERT INTO data VALUES (?);' )->execute( array($binary[$i]) );
$data = $db->query( 'SELECT binary FROM data;' )->fetchAll( PDO::FETCH_COLUMN );
for( $i = 0; $i < $num_values; $i++ )
if( $data[$i] != $binary[$i] ) echo "[$i] mismatch\n";
$db = null;
?>