0

Database:

CREATE TABLE `users_IPs` (
  `IP6` decimal(16,0) NOT NULL,
  PRIMARY KEY (`IP6`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

We want to insert an IPv6 address into this table:

$dsn = 'mysql:dbname=test;host=localhost';
$user = 'user';
$password = 'secret';

try {
    $dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
    $error = 'ERROR (1-CONNECT) ACCOUNT NOT READY'.$e->getMessage();
    return false;
  }

$sql = "INSERT INTO users_IPs SET IP6=:IP6
              ON DUPLICATE KEY UPDATE IP6=:IP6";

//Here we get an array of 16 unsigned bytes
//representing the IPv6 address
$IP6 = inet_pton("fe80::2e0:4cff:feb0:f8d");

$stmt = $dbh->prepare($sql);

//the problem is here
//tried PDO::PARAM_LOB, but it doesn't work
$stmt->bindParam(':IP6', $IP6, PDO::PARAM_LOB);
$result = $stmt->execute();

if ($result === false)
{
    print $stmt->errorInfo();
    return false;
}

$sql = "SELECT IP6 FROM users_IPs;";
$stmt = $dbh->prepare($sql);
$result = $stmt->execute();
$IP = $stmt->fetchColumn(0);

//string(1) "0" <- ? Just 1 byte
var_dump($IP);
//PHP Warning:  inet_ntop(): Invalid in_addr value
$IP =  inet_ntop($IP);
//outputs: bool(false)
var_dump($IP);

In the database the value for this column is "0". So, it seems that PDO doesn't save $IP6 as an array of bytes, but converts it in some way. Which make the value incorrect.

user4035
  • 22,508
  • 11
  • 59
  • 94

0 Answers0