我试图在数据库中保存远程用户IP。出于此目的,我已将列创建为int(10) UNSIGNED
。
当我尝试这样做时,一切正常,但IP保存为127.0.0.1
$ipaddr = $_SERVER['REMOTE_ADDR'];
$stmt = $pdo->prepare('INSERT INTO comment (body, author, email, date, url, ip) VALUES (:body, :author, :email, NOW(), :url, :ipaddr)');
$stmt->execute(array(
':body' => $_POST['k3jZGEeX1k1oo'],
':author' => $_POST['k3k0xKicU0eHQ'],
':email' => $email,
'url' => $url,
'ip' => $ipaddr
));
当我尝试使用INET_ATON
时,数据库中没有任何内容。
$ipaddr = $_SERVER['REMOTE_ADDR'];
$stmt = $pdo->prepare('INSERT INTO comment (body, author, email, date, url, ip) VALUES (:body, :author, :email, NOW(), :url, :INET_ATON(ipaddr))');
$stmt->execute(array(
':body' => $_POST['k3jZGEeX1k1oo'],
':author' => $_POST['k3k0xKicU0eHQ'],
':email' => $email,
'url' => $url,
'ip' => $ipaddr
));
请注意:INET_ATON(ipaddr)
。我如何用准备好的陈述来做到这一点?
答案 0 :(得分:1)
正如@ Fred-ii-所说,你应该检查错误。我也可以推荐this solution并构建php函数ip2long。在你的情况下将是
$ipaddr = $_SERVER['REMOTE_ADDR'];
$ip = sprintf("%u", ip2long($ipaddr));
$stmt = $pdo->prepare('INSERT INTO comment (body, author, email, date, url, ip) VALUES (:body, :author, :email, NOW(), :url, :ip)');
$stmt->execute(array(
':body' => $_POST['k3jZGEeX1k1oo'],
':author' => $_POST['k3k0xKicU0eHQ'],
':email' => $email,
':url' => $url,
':ip' => $ip
));
要选择并查看实际的IP,您可以在查询中使用INET_NTOA
(同样来自@ Fred-ii-评论)。