6

I was wondering if it is possible to convert a string to varbinary with PHP to get the same effect as with using the SQL function CONVERT(varbinary, 'data') I would like to do this because I am using codeigniter and would like to use active records for this query, and because of this not directly use a string of SQL, but I need to insert the data into a varbinary field in MS-SQL.

Thanks :)

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Zen
  • 7,197
  • 8
  • 35
  • 57

3 Answers3

6

you can cast a string as a binary if you are using a recent enough version of PHP.

$binary = (binary)$string;

(binary) casting and b prefix forward support was added in PHP 5.2.1

http://www.php.net/manual/en/language.types.type-juggling.php

dqhendricks
  • 19,030
  • 11
  • 50
  • 83
3
public static function str2bin($str) { 
  return '0x'.strtoupper(bin2hex($str));
}
Till
  • 31
  • 1
  • 1
    Thanks Till, this helped me immensely when converting the other way. `$data = hex2bin(substr($data, 2));` – Brett Jan 23 '18 at 04:11
  • This is exactly what I was looking for, but it returns me a binary value as a string. Is there any way around this as I need a raw binary value to insert into a database, not varchar. – Riples Nov 10 '20 at 00:01
0

You can also use the pack function

example convert {326546, 4356345, 43646346, 366357547} to var-binary as Unsigned int

$_BIN=pack('I*', 326546, 4356345, 43646346, 366357547);

you can find more examples at http://www.php.net/manual/en/function.pack.php

Gibnem
  • 675
  • 1
  • 8
  • 9