How can PHP be used to display real-time visitor statistics on a website?

To display real-time visitor statistics on a website using PHP, you can store visitor information in a database and then query the database to retrieve and display the data. You can use AJAX to periodically update the statistics without refreshing the entire page, providing a real-time experience for users.

<?php
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "visitor_stats";

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

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

// Query the database to get visitor statistics
$sql = "SELECT COUNT(*) as total_visitors FROM visitors";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    $row = $result->fetch_assoc();
    echo "Total Visitors: " . $row["total_visitors"];
} else {
    echo "0 results";
}

$conn->close();
?>