V Posted June 25, 2010 Share Posted June 25, 2010 I made my first script today for showing most viewed posts by unique IP addresses. I'm pretty proud of this one It seems to work fine, I'm just anticipating your thoughts and approval How it works: I have a unique_views table that records all IP addresses visiting a post and the post id. Then in the "posts" table I have a "views" field that shows the number of unique IP addresses that visited the post. The script that inserts IPs into the unique_views table require_once("functions.php"); $connection = dbConnect(); //connects to the DB $_SERVER['REMOTE_ADDR']; //retrieves visitor's IP $ip = $_SERVER['REMOTE_ADDR']; $post=$_GET['post']; //gets the post id $sql = "SELECT * FROM unique_views WHERE ip = '$ip' AND post_id = '$post'"; $result = $connection->query($sql) or die(mysqli_error($connection)); if (mysqli_num_rows($result) == 0) { $sql = "INSERT INTO unique_views (ip, post_id) VALUES ('$ip', '$post')"; $result = $connection->query($sql) or die(mysqli_error($connection)); $sql = "UPDATE posts set views=views+1 where post_id='$post'"; //adds +1 to the views field in posts table whenever a unique visitor visits the post $result = $connection->query($sql) or die(mysqli_error($connection)); } else { //show the total number of unique visitors $unique = mysqli_num_rows($result); echo "Unique views: $unique <br /><br />"; } and this script displays the most viewed posts require_once("functions.php"); $connection = dbConnect(); $sql = "SELECT post_title, views FROM posts WHERE views>1 ORDER BY views DESC"; $result = $connection->query($sql) or die(mysqli_error($connection)); while ($row = $result->fetch_assoc()) { $post_title=$row['post_title']; echo $post_title; echo "<br />"; } Link to comment https://forums.phpfreaks.com/topic/205881-my-most-viewed-posts-script-what-do-you-think/ Share on other sites More sharing options...
Recommended Posts