I'm trying to count page views on page load, although anytime I load the page 'UPDATE SET views = views + 1' is actually adding 2. I've got my code below, if any one has any suggestions that'd be awesome.
// Create database connection
$db = new mysqli($db[host], $db[user], $db[pass], $db[data]);
// Display database connection error (if applicable)
if (mysqli_connect_errno()){
printf("Connect failed: %s
", mysqli_connect_errno());
exit();
}
// Define Visitor Variables
$visitor[ip] = $_SERVER['REMOTE_ADDR']?:($_SERVER['HTTP_X_FORWARDED_FOR']?:$_SERVER['HTTP_CLIENT_IP']);
// Checks database to see if ip exists in logs
$check[ip] = $db->query("SELECT ip FROM admin_views WHERE ip = '$visitor[ip]'");
// If ip is found in database, update page views counter if it's not found, create a record for it
if ($check[ip]->num_rows == 1){
$db->query("UPDATE admin_views SET views = views +1 WHERE ip = '$visitor[ip]'");
} else {
$db->query("INSERT INTO admin_views VALUES('NULL', '$visitor[ip]')");
echo "not found";
}
// Count the number of views
$count_views = "SELECT SUM(views) AS countViews FROM admin_views";
if ($result = $db->query($count_views)) {
while ($row = $result->fetch_assoc()) {
$views = $row['countViews'];
}
$result->free();
}
// Count unique page views
$count_unique_views = "SELECT id FROM admin_views ORDER BY id DESC LIMIT 1";
if ($result = $db->query($count_unique_views)) {
while ($row = $result->fetch_assoc()) {
$unique_views = $row['id'];
}
$result->free();
}
// Close database connection
$db->close();