How can PHP be used to automatically update a dropdown menu when new data is added to a database?

When new data is added to a database, we can use PHP to dynamically update a dropdown menu by fetching the latest data from the database and populating the dropdown menu with the updated options. This can be achieved by making an AJAX call to a PHP script that queries the database for the new data and returns it as a JSON response. The dropdown menu can then be updated with the new options using JavaScript.

<?php
// Connect to the database
$conn = new mysqli("localhost", "username", "password", "dbname");

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

// Query to fetch the latest data from the database
$sql = "SELECT id, name FROM table_name ORDER BY id DESC";
$result = $conn->query($sql);

// Fetch data and store in an array
$data = array();
while($row = $result->fetch_assoc()) {
    $data[] = $row;
}

// Return data as JSON response
header('Content-Type: application/json');
echo json_encode($data);

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