I’m storing a guid(that actually points to a filename) as a Binary 16 in mysql. I’m using this function to generate the guid
private function guid(){
if (function_exists('com_create_guid') === true) {
return trim(com_create_guid(), '{}');
}
return sprintf('%04X%04X-%04X-%04X-%04X-%04X%04X%04X', mt_rand(0, 65535), mt_rand(0, 65535),
mt_rand(0, 65535), mt_rand(16384, 20479), mt_rand(32768, 49151), mt_rand(0, 65535),
mt_rand(0, 65535), mt_rand(0, 65535));
}
I’m saving the guid as binary using the function
$binary = pack("h*", str_replace('-', '', $guid ));
The problem is now when converting the binary field from the database back to guid to link the file, I dont get the original guid generated by the guid function above, I use this mysql statement to convert the binary 16 back to guid:
CONCAT(
HEX(SUBSTRING(hash,4,1)), HEX(SUBSTRING(hash,3,1)),
HEX(SUBSTRING(hash,2,1)), HEX(SUBSTRING(hash,1,1)) , '-',
HEX(SUBSTRING(hash,6,1)),HEX(SUBSTRING(hash,5,1)),'-',
HEX(SUBSTRING(hash,8,1)) , HEX(SUBSTRING(hash,7,1)),'-',
HEX(SUBSTRING(hash,9,2)),'-',HEX(SUBSTRING(hash,11,6))
)
where hash is the binary 16 field. Any Clue?
Thanks.
In your CONCAT, you seem to treat some parts as big-endian, others as small-endian. I believe HEX() will be returning big-endian, so you should be using “H*” in your pack, not “h*”. Then you should be able to treat the bytes in order: HEX(SUBSTRING(hash,1,4)), ‘-‘, HEX(SUBSTRING(hash,5,2)), ‘-‘, HEX(SUBSTRING(hash,7,2)), ‘-‘, HEX(SUBSTRING(hash,9,2)), ‘-‘, HEX(SUBSTRING(hash,11,6))
Also, you might want to know MySQL has a UUID() function. It might be easier for you to use e.g. UNHEX(REPLACE(UUID(), ‘-‘, ”)) when storing the string in the database, rather than pack, so that you know the same transformation is being used in both directions.