tags:

views:

45

answers:

2

How can I store the result of:

$store = md5("test", true);

mysql_query(...)

in a mysql db with a string query?

+1  A: 

Create a BINARY(16) field with index.

$store = md5("test", true);
mysql_query("INSERT INTO `Table` (`Field`) VALUES ('$store')");
Alexander.Plutov
I escape the value $store with mysql_real_escape_string, this is correct? I can save a binary string using ('$store') ?
Wiliam
yes, you can. Escaping is very good practice.
Alexander.Plutov
@Alexander.Plutov: But... md5(..., true) returns a binary string, that can be combined with a normal string? O.o
Wiliam
@Alexander.Plutov: http://php.net/manual/es/function.mysql-real-escape-string.php escape is required for binary strings, if not = error
Wiliam
+1  A: 

If you want to store it in binary format, you should pass binary data as hex to MySQL:

$md5 = md5('test'); // Returns MD5 in HEX
mysql_query("INSERT INTO `table` (`field`) VALUES (0x" . $md5 . ")");

Don't worry about MySQL handling this as integer, it won't. So if the field is declared as BINARY/BLOB, the hexadecimal value will be interpreted as binary.

DASPRiD
this is better practice than using "VALUES ('$store')" ?
Wiliam
Sure, because binary in a usual query string can make problems. So it is safer to transfer them encoded.
DASPRiD
@DASPRiD: But, what I need is to store the md5 in rawformat in a BINARY(16) field.
Wiliam
That's exactly what it'll be doing with this code.
DASPRiD
@DASPRiD: This is a valid solution. But I'm going to pass it as binary rawformat escaped. Is shorter, no conversion and it works better with my query framework. Thanks.
Wiliam