Create a Live Search Box with PHP and MySQL
Implement an interactive live search box using PHP, MySQL, and AJAX , no framework required!
🔍 Live Search Input
📜 JavaScript for Live Search
<script>
function liveSearch() {
let input = document.getElementById("search").value;
if (input.length === 0) {
document.getElementById("results").innerHTML = "";
return;
}
fetch("search.php?q=" + encodeURIComponent(input))
.then(response => response.text())
.then(data => {
document.getElementById("results").innerHTML = data;
});
}
</script>
📄 PHP Script: search.php
<?php
if (!isset($_GET['q'])) exit;
$q = trim($_GET['q']);
if ($q === '') exit;
$pdo = new PDO("mysql:host=localhost;dbname=demo", "user", "pass");
$stmt = $pdo->prepare("SELECT username FROM users WHERE username LIKE ? LIMIT 10");
$stmt->execute(["%$q%"]);
while ($row = $stmt->fetch()) {
echo htmlspecialchars($row['username']) . "
";
}
?>
🧠 How It Works
- JavaScript: Sends request to server on key press
- PHP: Uses prepared statements to fetch matching usernames
- Output: Results displayed live under the input
✅ Best Practices
-
Always use
htmlspecialchars()
when outputting user input - Use
LIMIT
in your SQL query to improve performance - Debounce AJAX calls to prevent overloading the server