TRYING TO WRITE A 12-byte string to PostgreSQL
Our code calculates a $number. We't then like to convert it to hex, pad it left with zeros and write it into a PostgreSQL bytea field. Easy, right?
(As an example) Would like it to return: \x000000002257 ('\x' + 12 bytes) ie, the left-padded HEX representation of the number 8791:
$number = 8791;
$hexnumber = str_pad(dechex($number), 12, '0', STR_PAD_LEFT);
$packed_hex = pack('h*', $hexnumber);
// BOTH of below produce: 000000002257
pg_raise('notice', "hexnumber: ".$hexnumber);
Cannot get any of these queries to update the bytea as I'd wish. Help!
//$query = ("UPDATE blobtest SET destfile = '".$hexnumber."' WHERE pkey = ".$args[0]);
// $query = ("UPDATE blobtest SET destfile = '000000002257' WHERE pkey = ".$args[0]);
// Above produces: \x303030303030303032323537
// (makes sense; it's quoted as a string)
// $query = ("UPDATE blobtest SET destfile = 000000002257 WHERE pkey = ".$args[0]);
// Above produces: ERROR: column "destfile" is of type bytea but expression is of type integer
// $query = ("UPDATE blobtest SET destfile = '8791' WHERE pkey = ".$args[0]);
// Above produces: \x38373931 as expected...
/ $query = ("UPDATE blobtest SET destfile = 8791 WHERE pkey = ".$args[0]);
// Above produces: ERROR: column "destfile" is of type bytea but expression is of type integer
// $query = ("UPDATE blobtest SET destfile = '"."'".$packed_hex."'"."' WHERE pkey = ".$args[0]);
// Above produces: \x only...
$query = ("UPDATE blobtest SET destfile = "."'".$packed_hex."'"." WHERE pkey = ".$args[0]);
// unterminated quoted string at or near "'"