I'm trying to add UUIDs to a couple of tables, but I'm not sure what the best way to store/retrieve these would be. I understand it's far more efficient to use BINARY(16) instead of VARCHAR(36). After doing a bit of research, I also found that you can convert a UUID string to binary with:
UNHEX(REPLACE(UUID(),'-',''))
Pardon my ignorance, but is there an easy way to this with PHP and then turn it back to a string, when needed, for readability?
Also, would it make much difference if I used this as a primary key instead of auto_increment?
EDIT:
Found part of the answer:
$bin = pack("h*", str_replace('-', '', $guid));
How would you unpack it?
Okay -- going to try to answer my own question. This is the best I could come up with:
Pack:
Unpack
Is there any problem with this anyone can see?
For php >= 5.4 we can use hex2bin and bin2hex:
Or using function for more organization:
For Laravel (using ID field):
As @Johan mentioned, you need to use uppercase H (Hex string, high nibble first) in order to be compatible with MySQL HEX / UNHEX functions
A more compact decode back to UUID function, using only
unpack()
andjoin()
methods. Attention: You need to name the unpack array parameters / keys in order not to be overwritten !And for older MySQL versions, where the
uuid_to_bin()
andbin_to_uuid()
functions are missing: