How can PHP be used to update database records when input fields are changed, preferably using the "onchange" event?

When input fields are changed, we can use JavaScript to trigger an AJAX request to a PHP script that updates the database records based on the new input values. By using the "onchange" event in the input fields, we can ensure that the database is updated whenever a change is made without requiring a page reload.

<?php
// PHP code to update database records based on input field changes

// Check if the request is an AJAX request
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    
    // Connect to the database
    $conn = new mysqli('localhost', 'username', 'password', 'database');

    // Get the new input value from the AJAX request
    $newInputValue = $_POST['newInputValue'];

    // Update the database records based on the new input value
    $sql = "UPDATE table SET column = '$newInputValue' WHERE id = 1";
    $conn->query($sql);

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