I am trying to make my own page hit counter but have run into some errors.
Firstly I get an error:
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given on line 21
Which correlates to this code:
<?php
// REQUIRE DB CONNECTION
$host = "host"; // Host name
$username = "username"; // Mysql username
$password = "password"; // Mysql password
$db_name = "database"; // Database name
$tbl_name = "info"; // Table name
$tbl_name2 = "hits"; // Table name
// Connect to server and select databse.
$conn = mysqli_connect($host, $username, $password)or die("cannot connect");
mysqli_select_db($conn, $db_name)or die("cannot select DB");
// CHECK IF PAGE EXISTS IN PAGE HIT TABLE
function checkPageName($page_name) {
global $conn, $tbl_name2;
$sql = "SELECT * FROM $tbl_name2 WHERE page = $page_name";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) == 0) {
$sql = "INSERT INTO $tbl_name2 (page, count) VALUES (:page, 0)";
$result = mysqli_query($conn, $sql);
}
}
// UPDATE PAGE HIT COUNT
function updateCounter($page_name) {
global $conn, $tbl_name2;
checkPageName($page_name);
$sql = "UPDATE $tbl_name2 SET count = count+1 WHERE page = $page_name";
$result = mysqli_query($conn, $sql);
}
// UPDATE VISITOR INFO
function updateInfo() {
global $conn, $tbl_name;
$ip_address = $_SERVER['REMOTE_ADDR'];
$user_agent = $_SERVER['HTTP_USER_AGENT'];
date_default_timezone_set('Europe/London');
$datetime = date("d/m/y H:i:s"); // create date and time
$sql = "INSERT INTO $tbl_name (ip_address, user_agent, time_accessed) VALUES($ip_address, $user_agent, $datetime)";
$result = mysqli_query($conn, $sql);
}
?>
The table info holds the ip address, user agent and time accessed, the hits table holds the page name and number of hits.
I call these functions on each page that I want to track. So for example I want to track my home page I add:
updateCounter("Home");
and updateInfo();
I tested this code by refreshing the page and right now it's not updating anything at all