php mysql updating IP address cannot work right

2019-08-28 03:14发布

问题:

The code is used to update the IP address user logged in. When I print the $sql string, it seems it is correct, the IP address is 1886883852, but after updated to mysql, the value is 2149463110. I have tried to set the data type in mysql as INT(11) bigint(12), all the same. If I try to write a string as

UPDATE ddns SET LastIP=1886883852, LastUpdate=now() WHERE ID=1

directly, without using any variable, it works correctly.

Really cannot understand. Anybody can help?

//get dns
function getIP(){
        //check the current ip address registered
        //Test if it is a shared client
        if (!empty($_SERVER['HTTP_CLIENT_IP'])){
          $ipaddr=$_SERVER['HTTP_CLIENT_IP'];
        //Is it a proxy address
        }elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
          $ipaddr=$_SERVER['HTTP_X_FORWARDED_FOR'];
        }else{
          $ipaddr=$_SERVER['REMOTE_ADDR'];
        }
        $ipaddr = ip2long($ipaddr);
        return $ipaddr;
}

$ipaddr = getIP();
$sql = "UPDATE ddns SET LastIP=$ipaddr, LastUpdate=now() WHERE ID=1";
echo $sql; **//here UPDATE ddns SET LastIP=1886883852, LastUpdate=now() WHERE ID=1**
$result = mysqli_query($dbh,$sql) or die("Query failed:");
**//Here after updated, the value of ipaddr in database is 2149463110**
if ($result)
        echo "Update ddns successfully";
else
        echo "faild to update ddns";

回答1:

Have you tried this way:

$sql = "UPDATE ddns SET LastIP='$ipaddr', LastUpdate=now() WHERE ID=1";

The IP address appears to be a string, so it needs to be quoted. Or you can var_dump the $_SERVER superglobal in order to check the field type. Or exceeding the limit of the memory.

Just for a testing case, you can change the field type to float, varchar or even text.



回答2:

Finally I find the reason. When I use Chrome to visit and update, the database will write 2149463110, when I use firefox or safari, the result will be 1886883852. Any explanation?



标签: php mysql ip