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