每次都会将插入的IP更改为MySQL数据库

I have a rating script that logs users' IPs so they can't rate the file more than once. However, every time I rate the file to test it, my $ip changes with the ip2long() function. What's up? Here's my code:

<?php

require('connect.php');

    $sheetID = $_GET["id"]; 
    $rating = $_GET["rating"];
$ip= $_SERVER['REMOTE_ADDR'];
$ip = ip2long($ip);

    $checkIPQuery = mysql_query("SELECT * FROM ratings WHERE sheetID = '$sheetID' and INET_NTOA(ip) = '$ip'");
    $doesIPExist = mysql_num_rows($checkIPQuery);
    if ($doesIPExist == 0) { 
        mysql_query("INSERT INTO ratings (sheetID, rating, ip) VALUES ($sheetID, $rating, $ip)"); 

        echo " $ip
<script>setTimeout(function(){location.href = '../sheets.php?id=$sheetID'},1);</script>"; 
    }
    else
        echo 'You have already rated this image!'; 

?>

And then for the check if the user has rated script:

$id = $_GET['id'];
$ip=$_SERVER['REMOTE_ADDR'];
$ip = ip2long($ip);

$checkIPQuery = mysql_query("SELECT * FROM ratings WHERE sheetID = '$id' and INET_NTOA(ip) = '$ip'");

$doesIPExist = mysql_num_rows($checkIPQuery);

Here's what I've done:

  • Changed the field to an unassigned INT when the $ip wouldn't go into a varchar(15)
  • I have added the ip2long() function because i changed the ip field to an INT
  • I then added the INET_NTOA(ip) to read the ip2long() INT

Any help would be appreciated. Thanks!

Edit: These scripts work fine if I set the $ip to 3 for example.

After reading the comments and a little research I found the answer and it is simple.

On 32-bit systems ip2long() returns negative and positive integers but INET_NTOA() only works with positive integers. So you have two options to fix that:

  1. Change your PHP code: $ip = sprintf('%u', ip2long($_SERVER['REMOTE_ADDR']));
  2. Change your SQL query: ... AND ip = " . ip2long($_SERVER['REMOTE_ADDR']) . " ...

You can verify this fact this way:

$ip  = $_SERVER['REMOTE_ADDR'];
$int = ip2long($ip);    
var_dump($ip, $int, sprintf('%u', $int));

This produces the following output:

string '192.168.1.120' (length=13)
int -1062731400
string '3232235896' (length=10)

Then go to MySQL:

mysql> SELECT '192.168.1.120', INET_NTOA(-1062731400), INET_NTOA(3232235896)
+---------------+------------------------+-----------------------+
| 192.168.1.120 | INET_NTOA(-1062731400) | INET_NTOA(3232235896) |
+---------------+------------------------+-----------------------+
| 192.168.1.120 | NULL                   | 192.168.1.120         |
+---------------+------------------------+-----------------------+
1 row in set (0.00 sec)