How can AJAX and JavaScript be integrated with PHP to enhance the functionality of displaying database queries in URLs?

When displaying database queries in URLs, it is important to ensure that sensitive information is not exposed. One way to enhance functionality is by using AJAX and JavaScript to dynamically load and display database query results without refreshing the page. This can be achieved by sending asynchronous requests to the server using JavaScript, which then interacts with PHP to fetch and process the data before returning it to the client-side for display.

<?php
// PHP code to handle AJAX request and fetch data from database

if(isset($_GET['query'])) {
    // Sanitize and validate the input
    $query = $_GET['query'];

    // Connect to the database
    $conn = new mysqli('localhost', 'username', 'password', 'database');

    // Perform the database query
    $result = $conn->query($query);

    // Fetch data and return as JSON
    $data = $result->fetch_all(MYSQLI_ASSOC);
    echo json_encode($data);

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