What is the recommended approach to automatically update a webpage when new data is available in a PHP application?

To automatically update a webpage when new data is available in a PHP application, you can use AJAX to periodically fetch new data from the server without refreshing the entire page. This can be achieved by setting up a JavaScript function that makes an AJAX request to a PHP script that fetches the latest data from the database. The fetched data can then be dynamically updated on the webpage without the need for a full page reload.

// PHP script to fetch latest data from the database
<?php
// Connect to database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

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

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

// Fetch latest data from database
$sql = "SELECT * FROM table ORDER BY id DESC LIMIT 1";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo json_encode($row);
    }
} else {
    echo "0 results";
}

$conn->close();
?>