What best practices should be followed when creating a loop to manage a hit counter in PHP?

When creating a loop to manage a hit counter in PHP, it is important to ensure that the loop is efficient and does not cause unnecessary strain on the server. One best practice is to store the hit count in a database or file rather than relying solely on a loop to increment the count. This will prevent issues with multiple users accessing the page simultaneously and ensure accurate counting.

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

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

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Get current hit count from database
$sql = "SELECT hits FROM counter";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    $row = $result->fetch_assoc();
    $hits = $row['hits'];
} else {
    $hits = 0;
}

// Increment hit count
$hits++;

// Update hit count in database
$sql = "UPDATE counter SET hits = $hits";
$conn->query($sql);

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

// Display hit count
echo "This page has been visited $hits times.";