Are there any best practices for integrating a visitor counter script in PHP?

When integrating a visitor counter script in PHP, it is important to ensure that the counter is accurately tracking unique visitors and not counting bots or repeated visits from the same user. One way to achieve this is by storing visitor information in a database and checking for unique visitors based on their IP address or other identifying information.

// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "visitors";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check if the visitor's IP address is already in the database
$ip_address = $_SERVER['REMOTE_ADDR'];
$query = "SELECT * FROM visitors WHERE ip_address = '$ip_address'";
$result = $conn->query($query);

if ($result->num_rows == 0) {
    // If the IP address is not in the database, insert a new record
    $insert_query = "INSERT INTO visitors (ip_address) VALUES ('$ip_address')";
    $conn->query($insert_query);
}

// Get the total number of unique visitors
$total_query = "SELECT COUNT(DISTINCT ip_address) AS total_visitors FROM visitors";
$total_result = $conn->query($total_query);
$total_visitors = $total_result->fetch_assoc()['total_visitors'];

echo "Total unique visitors: " . $total_visitors;

// Close the database connection
$conn->close();