問題描述
可能的重復(fù):
如何在 mySQL 中存儲 IP
我想從 $_SERVER['REMOTE_ADDR']
和其他一些 $_SERVER
變量中獲取 IP 地址,哪種數(shù)據(jù)類型適合于此?>
是VARCHAR(n)
嗎?
由于 IPv4 地址是 4 字節(jié)長,您可以使用 INT
(UNSIGNED
) 正好有 4 個字節(jié):
`ipv4` INT UNSIGNED
和 INET_ATON
和 INET_NTOA
轉(zhuǎn)換它們:
INSERT INTO `table` (`ipv4`) VALUES (INET_ATON("127.0.0.1"));SELECT INET_NTOA(`ipv4`) FROM `table`;
對于 IPv6 地址,您可以使用 BINARY
代替:
`ipv6` BINARY(16)
并使用 PHP 的 inet_pton
和 inet_ntop
用于轉(zhuǎn)換:
'INSERT INTO `table` (`ipv6`) VALUES ("'.mysqli_real_escape_string(inet_pton('2001:4860:a005::68')).'")''從`表`中選擇`ipv6`'$ipv6 = inet_pton($row['ipv6']);
Possible Duplicate:
How to store an IP in mySQL
I want to get the IP address from $_SERVER['REMOTE_ADDR']
and some other $_SERVER
variables, which datatype is the right one for this?
Is it VARCHAR(n)
?
Since IPv4 addresses are 4 byte long, you could use an INT
(UNSIGNED
) that has exactly 4 bytes:
`ipv4` INT UNSIGNED
And INET_ATON
and INET_NTOA
to convert them:
INSERT INTO `table` (`ipv4`) VALUES (INET_ATON("127.0.0.1"));
SELECT INET_NTOA(`ipv4`) FROM `table`;
For IPv6 addresses you could use a BINARY
instead:
`ipv6` BINARY(16)
And use PHP’s inet_pton
and inet_ntop
for conversion:
'INSERT INTO `table` (`ipv6`) VALUES ("'.mysqli_real_escape_string(inet_pton('2001:4860:a005::68')).'")'
'SELECT `ipv6` FROM `table`'
$ipv6 = inet_pton($row['ipv6']);
這篇關(guān)于哪個 MySQL 數(shù)據(jù)類型用于 IP 地址?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!