PHP AJAX Live Search Example
🔎 PHP AJAX Live Search Example
A Live Search allows users to see search results in real-time as they type. Using AJAX and PHP, we can fetch matching data from MySQL without reloading the page.
1️⃣ Database Setup
Table: users
| id | name | |
|---|---|---|
| 1 | Vipul | vipul@example.com |
| 2 | Amit | amit@example.com |
| 3 | Ravi | ravi@example.com |
| 4 | Priya | priya@example.com |
2️⃣ PHP Script to Fetch Search Results (search.php)
3️⃣ HTML + JavaScript (index.html)
4️⃣ How It Works
-
User types in the search input field.
-
onkeyuptriggers the liveSearch() function. -
AJAX sends the search query to
search.php. -
PHP queries MySQL database for matching records.
-
Results are returned and displayed in the
div#resultwithout reloading the page.
5️⃣ Key Points
-
Use
LIKE '%query%'in SQL for partial matches. -
Always sanitize user input to prevent SQL injection.
-
AJAX improves user experience by showing results in real-time.
-
Can be enhanced with JSON responses for more complex data.
-
Ideal for user directories, product search, or autocomplete fields.
