How can PHP and JavaScript be effectively integrated for live search functionality on a website?

To implement live search functionality on a website, PHP can be used to fetch search results from a database and JavaScript can be used to dynamically update the search results on the webpage without reloading the page. This can be achieved by sending an AJAX request from JavaScript to a PHP script that queries the database and returns the results in JSON format. The JavaScript then processes the JSON data and updates the search results on the webpage in real-time.

<?php
// search.php - PHP script to fetch search results from database

// Connect to database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);

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

// Fetch search results based on user input
$searchTerm = $_GET['searchTerm'];
$sql = "SELECT * FROM products WHERE name LIKE '%$searchTerm%'";
$result = $conn->query($sql);

// Return results in JSON format
$searchResults = array();
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $searchResults[] = $row;
    }
}
echo json_encode($searchResults);

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