Question

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.");"
Was it helpful?

Solution

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 );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top