tags:

views:

212

answers:

2

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?

A: 

Okay -- going to try to answer my own question. This is the best I could come up with:

Pack:

$binary =  pack("h*", str_replace('-', '', $string));

Unpack

$string = unpack("h*", $binary);
$string = preg_replace("/([0-9a-f]{8})([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]{12})/", "$1-$2-$3-$4-$5", $string);

Is there any problem with this anyone can see?

Greg
A: 

Greg, This is working fine but I am having trouble retrieving by the binary value. What type is your mysql field?

Brent

BINARY(16) -- remember to escape your query if you're not using prepared statements or the binary string will punch mysql in the mouth.
Greg
also -- just so you know in the future, you should post things like this as a comment rather than an answer
Greg