Advertisement
DigitMagazine

Store the User’s IP address, page views and visitor count

Feb 25th, 2015
241
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1. Store the User’s IP address, page views and visitor count:
  2.  
  3. $sql = “INSERT INTO visit (ip_address, visit_count) VALUES(‘$user_ip’, ‘1’) ON DUPLICATE KEY UPDATE visit_count=visit_count+1”; //8
  4. $add_ip = mysql_query($sql, $connection); //9
  5. if(! $add_ip )//10
  6. {
  7. die(mysql_error());//11
  8. }
  9.  
  10. The above code is the most important one, as it’s responsible for storing the user’s IP address along with the number of page views by that IP address. We’re using the “INSERT … ON DUPLICATE KEY UPDATE” syntax. There are other ways also to achieve the same result, but they call for avoidable and unnecessary coding. The 8th line contains this syntax and will store the value of variable “$user_ip” in “ip_address” column and value ‘1’ in the “visit_count” column. However, if the “ip_address” already exists, then instead of storing the IP address again, it will increment the “visit_count” column corresponding to that IP address by 1. The 9th line will now execute the 8th line along with 4th line. The 10th line checks whether the 9th line was successful in adding information to the database. If not, then the 11th line will display the error. If you want, you can remove the 10th and 11th line, since they’re helpful only during development.
  11. $sql2 = mysql_query(“SELECT ip_address FROM visit”);//12
  12. $total_visitors = mysql_num_rows($sql2);//13
  13.  
  14. $sql3 = mysql_query(‘SELECT SUM(visit_count) AS total FROM visit’); //14
  15. $fetch = mysql_fetch_assoc($sql3); //15
  16. $sum = $fetch[‘total’];//16
  17. ?>
  18.  
  19. This part is easy. All it does is count the total number of visitors by counting the number of rows in the “ip_address” column and then storing it in variable “$total_visitors”. This is done by line 12 and 13. Line 14 and 15 will sum up all the numbers in the “visit_count” column, while line 16 will store the result in variable “$sum”.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement