将IP与SQL表值进行比较

时间:2013-07-16 13:25:26

标签: php sql ip

我在使用以下内容提交表单时捕获访问者IP地址。

$users_ip=$_SERVER['REMOTE_ADDR'];

我现在要做的是看看在提交评论之前是否使用了这个ip变量,有人能指出我正确的方向吗?

可能是like SQL命令?

2 个答案:

答案 0 :(得分:1)

假设您将客户端ips存储在名为“ips”的表中,请使用:

$connection = mysql_connect($your_db_host, $your_user_account, $your_password);
$mysql_select_db($your_db_name);

$ip = $_SERVER['REMOTE_ADDR'];
$sql = "select 1 from `ips` where `ip`='$ip'";
$sql_resource = mysql_query($sql);
$mysql_close($connection);

if($sql_resource && mysql_num_rows($sql_resource) > 0){
    // your logic code if the ip existed in the db
    echo 'The ip has been used before';
} else {
    // code if the ip not existed in the db
    echo 'The ip has not been used before yet';
}

答案 1 :(得分:1)

有一个很好的教程解释如何在MySQL中存储IP地址。简而言之,将它们转换为this comment中建议的长,然后使用简单的SELECT语句来查找它:

"SELECT COUNT(*) FROM comment WHERE ip = " . ip2long($_SERVER['REMOTE_ADDR'])