Generic_User_ID
Generic_User_ID

Reputation: 1207

When I try to insert ip2long Integer, the wrong Integer gets inserted into table

My code:

$ip = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'][0]); // Gives an IP address string. Example: "176.10.99.207"

$ipL = ip2long($ip); // An integer, which for this example would be 2953470927.

if( $stmt_insert_ip = $ip_link->prepare("INSERT INTO dataTable(ip,datetime) VALUES(?,?)") ){
  $stmt_insert_ip->bind_param('is',$ipL,date("Y-m-d H:i:s"));
}

But when I check my MySQL table, the newly-inserted value under the ip column is 2147483647, which is "127.255.255.255".

When I run echo($ipL);, however, I get 2953470927.

What the H-E-Double hockey sticks is going on here?

Upvotes: 1

Views: 327

Answers (2)

Wh1T3h4Ck5
Wh1T3h4Ck5

Reputation: 8509

I assume you have used INT as datatype in your database. To make this story short just change datatype of ip column to BIGINT and problem will be solved.

INT range (-2147483648, 2147483647)
BIGINT range (-9223372036854775808, 9223372036854775807)

2953470927 goes bit over the range of signed INT.

Refference: MySQL: Integer types

Upvotes: 1

Jonathan
Jonathan

Reputation: 2877

Unfortunately depending on your system (32-bit vs 64-bit) PHP returns different values.

on a 32-bit system it uses signed integers, and on a 64-bit machine it uses unsigned integers, so you'll need to store the data accordingly.

Based on what you returned it seems like you're using a 64-bit machine, so change your mysql column to an unsigned integer, or a signed or unsigned bigint

Upvotes: 1

Related Questions