What are the best practices for integrating a counter function with PHP scripts?

When integrating a counter function with PHP scripts, it is important to ensure that the counter is accurately incremented and stored in a persistent manner. One common approach is to use a database to store the counter value and update it accordingly in the PHP script. Additionally, it is important to consider concurrency issues and implement proper locking mechanisms to prevent race conditions.

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

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

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

// Retrieve current counter value
$sql = "SELECT counter FROM counter_table";
$result = $conn->query($sql);

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

// Increment counter
$counter++;

// Update counter value in database
$sql = "UPDATE counter_table SET counter = $counter";
$conn->query($sql);

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

// Display counter value
echo "Counter: " . $counter;