Table of Contents:
PHP AJAX Autocomplete Tutorial – Complete Beginner Guide
Autocomplete improves user experience by suggesting possible values as users type in an input field. It is commonly used in search boxes, form inputs, city selection, email suggestions, and product names.
This tutorial explains how to build a PHP AJAX autocomplete system using MySQL, with clear examples and output.
What Is Autocomplete in PHP AJAX?
Autocomplete is a feature where:
- User types in an input field
- AJAX sends the typed value to PHP
- PHP fetches matching data from MySQL
- Suggestions appear below the input field
- Page does not reload
Why Use AJAX Autocomplete?
Autocomplete helps to:
- Improve form usability
- Reduce typing errors
- Speed up data entry
- Enhance user experience
Technologies Used in PHP AJAX Autocomplete
- HTML for input field
- JavaScript for AJAX requests
- PHP for server-side processing
- MySQL for suggestion data
Prerequisites for Autocomplete Tutorial
Before starting, you should know:
- Basic HTML
- Basic JavaScript
- PHP fundamentals
- MySQL SELECT and LIKE
Sample MySQL Table Used for Autocomplete
CREATE TABLE cities (
id INT AUTO_INCREMENT PRIMARY KEY,
city_name VARCHAR(100)
);
PHP MySQL Database Connection File
<?php
$conn = mysqli_connect("localhost", "root", "", "testdb");
if (!$conn) {
die("Database connection failed");
}
?>
Step 1: Create HTML Input Field
<!DOCTYPE html>
<html>
<head>
<title>PHP AJAX Autocomplete</title>
<style>
#suggestions {
border: 1px solid #ccc;
max-width: 300px;
}
.item {
padding: 5px;
cursor: pointer;
}
.item:hover {
background-color: #f0f0f0;
}
</style>
<script>
function getSuggestions(value) {
if (value.length == 0) {
document.getElementById("suggestions").innerHTML = "";
return;
}
var xhr = new XMLHttpRequest();
xhr.open("GET", "autocomplete.php?query=" + value, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("suggestions").innerHTML = xhr.responseText;
}
};
xhr.send();
}
function selectValue(value) {
document.getElementById("search").value = value;
document.getElementById("suggestions").innerHTML = "";
}
</script>
</head>
<body>
<input type="text" id="search" onkeyup="getSuggestions(this.value)" placeholder="Enter city name">
<div id="suggestions"></div>
</body>
</html>
Step 2: Create PHP Autocomplete Script (autocomplete.php)
<?php
include "db.php";
$keyword = $_GET['query'];
$sql = "SELECT city_name FROM cities WHERE city_name LIKE '%$keyword%' LIMIT 5";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
echo "<div class='item' onclick=\"selectValue('".$row['city_name']."')\">";
echo $row['city_name'];
echo "</div>";
}
?>
Output While Typing “del”
Delhi
Typing “mu”:
Mumbai
Suggestions appear instantly below the input field.
Secure Autocomplete Using Prepared Statement
<?php
include "db.php";
$stmt = mysqli_prepare($conn,
"SELECT city_name FROM cities WHERE city_name LIKE ? LIMIT 5");
$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 "<div class='item'>".$row['city_name']."</div>";
}
?>
Difference Between Live Search and Autocomplete
| Feature | Live Search | Autocomplete |
|---|---|---|
| Displays full results | Yes | No |
| Suggests values | No | Yes |
| Input focus | Optional | Required |
| Usage | Search pages | Forms |
PHP AJAX autocomplete, PHP autocomplete tutorial, AJAX input suggestion PHP, PHP MySQL autocomplete, PHP AJAX autocomplete example
Common Mistakes in Autocomplete Implementation
- No result limit
- Missing input validation
- Not hiding suggestion box
- Poor UI styling
Best Practices for PHP AJAX Autocomplete
- Use LIMIT to restrict results
- Use prepared statements
- Add indexes on searchable columns
- Hide suggestions when empty
- Improve UX with CSS
Related tutorial
Frequently Asked Questions (FAQ)
1. What is autocomplete in PHP?
It suggests values while the user types.
2. Does autocomplete reload the page?
No, it works asynchronously.
3. Is autocomplete secure?
Yes, with prepared statements.
4. Can autocomplete work without database?
Yes, with static data.
5. Is autocomplete good for forms?
Yes, especially for large datasets.