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();
}
?>
Keywords
Related Questions
- What best practices should be followed when incorporating line breaks in PHP output from a database?
- What are the potential security risks associated with storing session data in cookies or LocalStorage in PHP?
- What best practices should be followed when using str_replace for manipulating local path strings in PHP?