PHP AJAX Live Search Tutorial

PHP AJAX Live Search – Complete Beginner Tutorial

A live search allows users to see search results while typing, without clicking a submit button or reloading the page. This feature is commonly used in search boxes, product filters, user lists, and admin panels.

This tutorial explains how to build a PHP AJAX live search using MySQL, with clear examples and outputs.


What Is Live Search in PHP AJAX?

Live search is a technique where:

  • JavaScript listens to user input
  • AJAX sends the typed text to PHP
  • PHP searches the database using MySQL
  • Results are returned instantly
  • The page updates without reload

Why Use AJAX Live Search?

Live search improves:

  • User experience
  • Search speed
  • Website interactivity
  • Data filtering efficiency

Examples include:

  • User search
  • Product search
  • Blog article search
  • Email or username lookup

Technologies Used in PHP AJAX Live Search

  • HTML for input field
  • JavaScript for AJAX request
  • PHP for server-side processing
  • MySQL for database search

Prerequisites for Live Search Tutorial

Before starting, ensure you know:

  • Basic HTML
  • Basic JavaScript
  • PHP fundamentals
  • MySQL SELECT and LIKE

Sample MySQL Table Used for Live Search

CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100),
    email VARCHAR(100)
);

PHP MySQL Database Connection File

<?php
$conn = mysqli_connect("localhost", "root", "", "testdb");

if (!$conn) {
    die("Database connection failed");
}
?>

Step 1: Create HTML Search Input

<!DOCTYPE html>
<html>
<head>
    <title>PHP AJAX Live Search</title>
    <script>
        function liveSearch(value) {
            if (value.length == 0) {
                document.getElementById("result").innerHTML = "";
                return;
            }

            var xhr = new XMLHttpRequest();
            xhr.open("GET", "search.php?query=" + value, true);

            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    document.getElementById("result").innerHTML = xhr.responseText;
                }
            };

            xhr.send();
        }
    </script>
</head>
<body>

<input type="text" onkeyup="liveSearch(this.value)" placeholder="Search user...">
<div id="result"></div>

</body>
</html>

Step 2: Create PHP Search Script (search.php)

<?php
include "db.php";

$query = $_GET['query'];

$sql = "SELECT * FROM users WHERE name LIKE '%$query%'";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
    while ($row = mysqli_fetch_assoc($result)) {
        echo $row['name'] . " (" . $row['email'] . ")<br>";
    }
} else {
    echo "No results found";
}
?>

Output While Typing “ra”

Rahul (rahul@gmail.com)
Ravi (ravi@gmail.com)

Results update instantly without page refresh.


Live Search with Prepared Statement (Secure Version)

<?php
include "db.php";

$stmt = mysqli_prepare($conn,
    "SELECT * FROM users WHERE name LIKE ?");
$search = "%" . $_GET['query'] . "%";
mysqli_stmt_bind_param($stmt, "s", $search);

mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);

while ($row = mysqli_fetch_assoc($result)) {
    echo $row['name'] . "<br>";
}
?>

Improve Live Search with LIMIT

SELECT * FROM users WHERE name LIKE '%keyword%' LIMIT 5;

This improves performance for large datasets.


Common Mistakes in AJAX Live Search

  • Not validating input
  • Missing debounce for fast typing
  • Searching without LIMIT
  • Not handling empty input

PHP AJAX live search, live search PHP MySQL, AJAX real time search PHP, PHP AJAX search example, PHP MySQL live search tutorial


Best Practices for PHP AJAX Live Search

  • Use prepared statements
  • Limit search results
  • Add indexes on search columns
  • Use debounce for better performance
  • Sanitize user input

Related tutorial:


Frequently Asked Questions (FAQ)

1. What is live search in PHP?

It displays search results while the user types.

2. Does live search require page reload?

No, it works without reloading.

3. Is live search secure?

Yes, when using prepared statements.

4. Can live search work with large databases?

Yes, with LIMIT and indexing.

5. Is AJAX required for live search?

Yes, for real-time updates.

Related Article
50+ PHP Interview Questions and Answers 2023

1. Differentiate between static and dynamic websites. Static Website The content cannot be modified after the script is executed The Read more

All We Need to Know About PHP Ecommerce Development

  Many e-commerce sites let you search for products, show them off, and sell them online. The flood of money Read more

PHP Custom Web Development: How It Can Be Used, What Its Pros and Cons Are,

PHP is a scripting language that runs on the server. It uses server resources to process outputs. It is a Read more

PHP Tutorial

PHP Tutorial – Complete Guide for Beginners to Advanced Welcome to the most comprehensive PHP tutorial available online at PHPOnline.in Read more

Introduction of PHP

Introduction to PHP – Learn PHP from Scratch with Practical Examples Welcome to your complete beginner's guide to PHP. Whether Read more

Syntax Overview of PHP

Syntax Overview of PHP (2025 Edition) Welcome to phponline.in, your one-stop platform for mastering PHP. This comprehensive, SEO-rich tutorial on Read more

Environment Setup in PHP

Setting Up PHP Environment (Beginner’s Guide) If you’re planning to learn PHP or start developing websites using PHP, the first Read more

Variable Types in PHP

PHP Variable Types: Complete Beginner's Guide to PHP Data Types Welcome to phponline.in, your trusted source for beginner-to-advanced level PHP Read more

Comments

No comments yet. Why don’t you start the discussion?

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    Prove your humanity: 2   +   3   =