简体   繁体   中英

unable to save remote ip address in mysql

I am having a weird issue: I want to save site visitor's IP address to database.below i am saying if visitor is not me (61.68.257.80 is my IP address), then save IP address to database. its worked fine when i checked by hiding my proxy. it was saving the ip addresses except mine, but when i visited the website from phone(with phone internet not WiFi) which has different IP address then it is not stored into database. Anyone?

$visitor=$_SERVER['REMOTE_ADDR'];
      if($visitor!=="61.68.257.80"){
           $count="SELECT * FROM `visitor`";
           $countRun=mysqli_query($conn,$count);
             while($countRow=mysqli_fetch_array($countRun)){
                   $current_counts=$countRow['counts'];
                   $new_count=$current_counts+1;
                 }
            $remote_ip= $_SERVER['REMOTE_ADDR'];
            $queryUpdate="INSERT INTO `visitor`(`counts`,`ip_address`)VALUES('".$new_count."','".$remote_ip."')";
            $runUpdate=mysqli_query($conn,$queryUpdate);

        }

One small suggestion to improve your code, meanwhile it will be faster too,

What you are doing is getting entire table records, and looping it and finally getting last record's counts, probably that could be maximum value.

So instead of this :

 $count="SELECT * FROM `visitor`";
           $countRun=mysqli_query($conn,$count);
             while($countRow=mysqli_fetch_array($countRun)){
                   $current_counts=$countRow['counts'];
                   $new_count=$current_counts+1;
                 }

You can just modify your query like below :

$count = "select max(counts) as count_max_value from visitor";

Above query will return just one row/record which you can access using key count_max_value .

For comments:

used var_dump and it gave me "string(13) then ip address" while in database its varchar(12).

You can modify your table using below query (for an IPv4 address)

ALTER TABLE `visitor` MODIFY `ip_address` VARCHAR(15);

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