How To Create a Live Search Box with PHP and MySQL

Implement a live search feature in PHP using MySQL and AJAX.

1 min read โ€ข
88 1 0

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

Comments (0)

No comments yet. Be the first to comment!

Leave a Comment

Replying to someone. Cancel