PHP AJAX Live Search Example

PHP Tutorial

🔍 PHP AJAX Live Search Example

AJAX Live Search allows users to search data in real time as they type—without reloading the page.
This is very common in search boxes, user lookup, product search, admin panels, etc.


1️⃣ What is AJAX Live Search?

  • User types in input box

  • AJAX sends request on each key press

  • PHP fetches matching data

  • Results appear instantly below input

📌 Also called Autocomplete / Instant Search


2️⃣ How It Works (Flow)

  1. User types text

  2. JavaScript sends AJAX request

  3. PHP queries database

  4. Matching records returned

  5. HTML updates dynamically


3️⃣ Database Table (Example)

students table


Sample data:

Amit
Ankit
Rahul
Ravi
Rohit
Neha

4️⃣ HTML + JavaScript (AJAX)

index.html


 


5️⃣ PHP File (Search Logic)

search.php


 

% → wildcard
$q% → starts with typed text


6️⃣ Output Example

Typing “Ra” shows:

Rahul
Ravi

✔ No page reload
✔ Real-time results


7️⃣ Improve Search (Anywhere Match)

WHERE name LIKE '%$q%'

📌 Matches text anywhere in the name


8️⃣ Security Improvement ⭐ (Interview)

Use Prepared Statements to prevent SQL Injection.

$stmt = $conn->prepare("SELECT name FROM students WHERE name LIKE ?");
$search = $q . "%";
$stmt->bind_param("s", $search);
$stmt->execute();
$result = $stmt->get_result();

9️⃣ Common Mistakes ❌

❌ Query on every keystroke without limit
❌ No input validation
❌ SQL injection risk
❌ Not handling empty input
❌ No index on searched column


🔟 AJAX Live Search vs Normal Search ⭐

Feature Live Search Normal Search
Page reload ❌ No ✔ Yes
User experience Fast Slower
Server calls More Less
Modern apps ✔ Yes ❌ Old

📌 Interview Questions & MCQs

Q1. What is AJAX Live Search?

A) Page reload search
B) Real-time search
C) Static search
D) Server-side search only

Answer: B


Q2. Which event is commonly used?

A) onclick
B) onchange
C) onkeyup
D) onsubmit

Answer: C


Q3. Which operator is used in SQL search?

A) IN
B) BETWEEN
C) LIKE
D) EXISTS

Answer: C


Q4. Best way to prevent SQL injection?

A) mysqli_query
B) Prepared statements
C) echo
D) htmlspecialchars

Answer: B


Q5. Live search improves?

A) Database size
B) UI/UX
C) Server load
D) Storage

Answer: B


🔥 Real-Life Use Cases

✔ Google-like search
✔ Admin user lookup
✔ Product search
✔ Email / username suggestions


✅ Summary

  • AJAX Live Search = real-time search

  • Uses JavaScript + PHP + MySQL

  • LIKE operator for matching

  • No page reload

  • Prepared statements for security

  • Very important for interviews & projects

You may also like...