This topic demonstrates how JavaScript Fetch API can be used to send search queries to PHP, which then retrieves filtered data from a MySQL database and returns it as JSON.
The Fetch API sends HTTP requests from JavaScript. PHP processes the request, queries the database, and responds with JSON data that JavaScript can easily parse and display.
// PHP script to search users table based on query string
query($sql);
$data = [];
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
echo json_encode($data);
$conn->close();
?>
The JavaScript Fetch API sends a search keyword to this PHP file. PHP executes the SQL query, fetches matching rows, converts them into JSON, and sends them back to JavaScript.
You can connect this PHP script with an input field and dynamically display results as users type, creating a live search experience similar to autocomplete.