How can one effectively retrieve data from a database using PHP and JavaScript in a continuous loop?

To continuously retrieve data from a database using PHP and JavaScript, you can create an AJAX request in JavaScript that calls a PHP script to fetch data from the database at regular intervals. The PHP script should query the database and return the data in a JSON format. The JavaScript function should handle the AJAX response and update the webpage with the retrieved data.

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

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

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

// Query your database for data
$sql = "SELECT * FROM your_table";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // Output data as JSON
    $data = array();
    while ($row = $result->fetch_assoc()) {
        $data[] = $row;
    }
    echo json_encode($data);
} else {
    echo "0 results";
}

$conn->close();
?>