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.


 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


 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


Database Table (Example)

students table

Sample data:

Amit
Ankit
Rahul
Ravi
Rohit
Neha

HTML + JavaScript (AJAX)

index.html


 


 PHP File (Search Logic)

search.php


 

  • % → wildcard
  • $q% → starts with typed text

 Output Example

Typing “Ra” shows:

Rahul
Ravi
  •  No page reload
  •  Real-time results

 Improve Search (Anywhere Match)

WHERE name LIKE '%$q%'

 Matches text anywhere in the name


 Security Improvement (Interview)

Use Prepared Statements to prevent SQL Injection.


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

FeatureLive SearchNormal Search
Page reload NoYes
User experienceFastSlower
Server callsMoreLess
Modern appsYesOld

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...