← Back to Chapters

PHP MySQL Search Data with Fetch API

? PHP MySQL Search Data with Fetch API

? Quick Overview

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.

? Key Concepts

  • Asynchronous data fetching using Fetch API
  • Passing query parameters from JavaScript to PHP
  • Searching MySQL records dynamically
  • Returning JSON responses

? Syntax / Theory

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.

? Code Example

? View Code Example
// 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();
?>

? Live Output / Explanation

How it works

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.

? Interactive Example

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.

? Use Cases

  • Live user search systems
  • Product search filters
  • Admin dashboards
  • Dynamic content loading

? Tips & Best Practices

  • Always use prepared statements to prevent SQL injection
  • Debounce user input to reduce server load
  • Send JSON responses with correct headers

? Try It Yourself

  • Create a search input using JavaScript fetch()
  • Render results in a table dynamically
  • Highlight matching keywords in results