Our first task will be inserting the visitors IP into our MySQL Table. PHP has a handy built in code called
$_SERVER['REMOTE_ADDR'] that will take the get the visitors IP address. We can use that code and store it into a variable to insert into our Database. The following code does that:
CODE
$ip = $_SERVER['REMOTE_ADDR'];
Now comes the magic. Once we have the visitors IP we need to check our table if the visitor has already visited your site or not. We can use an If/Else statement to do this very easily.
CODE
$fetch = mysql_query("SELECT ip FROM $tbl_name WHERE ip ='".$ip."'") or die(mysql_error());
if ( mysql_num_rows($fetch) == 0 ) {
mysql_query("INSERT INTO $tbl_name(ip,visits) VALUES('$ip','1')") or die(mysql_error());
} else {
mysql_query("UPDATE $tbl_name SET visits=visits+1 WHERE ip = '$ip'") or die(mysql_error());
}
$fetch is suppose to select the row of our MySQL table that contains the IP address of our visitor. If $fetch equals 0, that means that the visitor has never visited your site before, because a row for his IP address and number of visits doesn't exist. In that case, we must insert the new visitors IP Address into the IP row of our table, and in the visits row of our table.
If the users IP was found already (meaning he has already visited the site at least once), all we need to do is add one to our visits row, next to his IP address. Our else statement does exactly that.
All that is left now is outputting our results!