在mysql中存储ip地址?

时间:2014-04-10 16:29:37

标签: php mysql

我正在尝试将用户IP地址存储到VARCHAR(39)下的mysql表中,但它只存储为"::1"

我正在使用此代码:

<?php
session_start();

$db_hostname = 'localhost';
$db_database = 'hewden1'; 
$db_username = 'root';
$db_password = '';

$db_server = mysql_connect($db_hostname, $db_username, $db_password)    
        or die("Unable to connect to MySQL: " . mysql_error());

mysql_select_db($db_database)   
or die("Unable to select database: " . mysql_error());

 $cname       = $_POST['cname'];
   $creg      = $_POST['creg'];  
   $address      = $_POST['address'];  
   $post      = $_POST['post'];  
   $contactn      = $_POST['contactn'];
   $contactt      = $_POST['contactt'];
   $email      = $_POST['email'];
   $vat     = $_POST['vat'];

    $ipaddress = $_SERVER["REMOTE_ADDR"];


$sql="INSERT INTO supplier_registration (company_name, company_reg_number, company_address, company_postcode, contact_name, contact_number, contact_email, company_vat_number, date_time, user_ip)
VALUES ('$cname', '$creg', '$address', '$post', '$contactn', '$contactt', '$email', '$vat', NOW(), '$ipaddress')";$result = mysql_query($sql); 

if($result){

echo "jobs a gooden";

}else {
echo "ERROR";
}
?>

有人可以告诉我我哪里出错了,谢谢

1 个答案:

答案 0 :(得分:2)

简单的解决方案,将您的ip列更改为varbinary (16)数据类型,然后使用以下内容存储ips:

$ip = bin2hex(inet_pton($_SERVER['REMOTE_ADDR']));

注意:请确保您的php版本是最新的,因为inet_pton()是一个新功能。