<coded>


PHP Search Autocomplete with Ajax (2025 Update)

September 15, 2025

Looking for a simple PHP search autocomplete script with Ajax?
In this tutorial, we’ll build a clean example that lets users type into a search box and instantly get suggestions from a MySQL database.

This step-by-step PHP Ajax search tutorial is perfect for beginners, SEO-friendly, and easy to copy-paste into your own project.


🚀 Features of this Script


🛠️ Step 1: Database Setup

Create a MySQL table named users and insert some sample data.

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

INSERT INTO users (name) VALUES
('Alice Johnson'),
('Bob Smith'),
('Charlie Brown'),
('David Miller'),
('Emma Wilson'),
('Frank Taylor'),
('Grace Lee'),
('Hannah Martin');

🛠️ Step 2: HTML Search Form (index.html)

This is the frontend with a simple input box and results dropdown.

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>PHP Search Autocomplete with Ajax</title>
    <style>
        body { font-family: Arial, sans-serif; padding: 30px; }
        .search-box { width: 300px; padding: 10px; }
        .result { border: 1px solid #ccc; max-width: 300px; }
        .result p { margin: 0; padding: 8px; cursor: pointer; }
        .result p:hover { background: #f2f2f2; }
    </style>
</head>
<body>
    <h1>PHP Search Autocomplete with Ajax</h1>
    <input type="text" class="search-box" id="search" placeholder="Search users...">
    <div class="result" id="result"></div>

    <script>
        document.getElementById("search").addEventListener("keyup", function() {
            let query = this.value;
            if(query.length > 0) {
                fetch("search.php?q=" + encodeURIComponent(query))
                    .then(response => response.text())
                    .then(data => {
                        document.getElementById("result").innerHTML = data;
                    });
            } else {
                document.getElementById("result").innerHTML = "";
            }
        });

        document.getElementById("result").addEventListener("click", function(e) {
            if(e.target && e.target.tagName === "P") {
                document.getElementById("search").value = e.target.textContent;
                this.innerHTML = "";
            }
        });
    </script>
</body>
</html>

🛠️ Step 3: PHP Backend (search.php)

This file queries the database and returns matching results.

<?php
// Database connection
$host = "localhost";
$db   = "test_db";
$user = "root";
$pass = "";

try {
    $pdo = new PDO("mysql:host=$host;dbname=$db;charset=utf8", $user, $pass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    die("Database connection failed: " . $e->getMessage());
}

if(isset($_GET["q"])) {
    $q = "%" . $_GET["q"] . "%";
    $stmt = $pdo->prepare("SELECT name FROM users WHERE name LIKE ? LIMIT 10");
    $stmt->execute([$q]);

    if($stmt->rowCount() > 0) {
        while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            echo "<p>" . htmlspecialchars($row["name"]) . "</p>";
        }
    } else {
        echo "<p>No results found</p>";
    }
}
?>
Did you find this useful? Please rate this post: