0

I have an ip table with VARBINARY fields: ip_start and ip_end Now I have a problem,

$ip=('2001:255:ffff:ffff:ffff:ffff:ffff:ffff');
$binary=unpack("A16",inet_pton($ip));
var_dump($binary);

Now, how to store $binary_start and $binary_end to ip table? Do I need any wrapping of data(such as bin2hex)?

"INSERT INTO `ip_table` (`id`, `binary_start`, `binary_end`) VALUES
(1,".$binary_start.",".$binary_end.");"
Álvaro González
  • 142,137
  • 41
  • 261
  • 360
werva
  • 1,589
  • 5
  • 16
  • 19
  • 3
    Possible duplicate of [How can I prevent SQL injection in PHP?](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php). Despite the title, that's the exact problem you're facing and solutions listed there will fix it. – Álvaro González Nov 05 '13 at 10:28
  • @CBroe - He already mentions `varbinary`. – Álvaro González Nov 05 '13 at 10:36

1 Answers1

1

MySQL has a BINARY/VARBINARY type, which could be used to store binary data directly, without compute it into a hexadecimal representation.

CREATE TABLE `%s` (
    `binary_start` BINARY( 20 ) NOT NULL,
    `binary_end` VARBINARY( 20 ) NOT NULL,
);

If you use prepared statements and pass the values without concatenating them to a string, the binary data will be inserted "as is".

/** @var $database \PDO */
$stmt = $database->prepare( 'INSERT INTO `ip_table` (`binary_start`, `binary_end`) VALUES ( :start, :end );' );
$stmt->bindValue( ':start', $binaryStart );
$stmt->bindValue( ':end', $binaryEnd );
feeela
  • 29,399
  • 7
  • 59
  • 71