简体   繁体   中英

Compare IP to SQL table values

I am capturing the visitors ip address during a form submit using the following.

$users_ip=$_SERVER['REMOTE_ADDR'];

What I would now like to do is see if this ip variable has been used before when submitting a comment, can anyone point me in the right direction?

Maybe a like SQL command?

Assuming you stored client ips in the table named: "ips" then use this:

$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';
}

There is a good tutorial explaining how to store IP addresses in MySQL. In short, convert them to long like suggested in this comment , then use simple SELECT statement to find it:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM