This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

📣 Introducing DigitalOceans General Purpose & CPU Optimized Servers on Cloudways Flexible. Learn More

How to Build Live Search Box Using PHP, MySQL and AJAX

Updated on December 4, 2024

7 Min Read
Key Takeaways:

  • A live search box uses JavaScript, PHP, and MySQL to show search results instantly as you type.
  • The JavaScript code sends your search query to a PHP script, which queries the database and sends back the results to be displayed on the page. Doing so makes searching faster and more interactive, improving user experience.

Have you ever wondered how websites suggest search terms as you type? This is called a live search box.

Instead of waiting for the whole page to load each time you search, live search boxes give you instant results. This makes searching easier and faster.

Live search boxes are made with JavaScript (jQuery), MySQL, PHP, and AJAX.

In this blog, we’ll show you how to make a live search box using PHP, MySQL, and AJAX. They work together to make your search feature dynamic and responsive.

PHP handles the server-side logic, MySQL stores and retrieves your data, and AJAX lets the page update search results without reloading the whole page.

Why Live Search Box Matters?

Users want things to be fast and easy today. When they can find results as they type, it saves them time and keeps them interested in your content or products.

A live search box makes it easier and faster for visitors to find what they’re looking for. Instead of going to different pages or waiting for a search to load, users get instant suggestions as they type.

A live search box can also help you sell more products, especially for online stores. By offering immediate results, it guides users to the exact product or category they want, so they don’t have to click on too many things.

Prerequisites for Live Search Box

  1. Code editor (Sublime or Notepad++ are good options)
  2. Apache and MySQL (either XAMPP or WAMP). In this article, I will use XAMPP.
  3. HTML, CSS, PHP, MySQL, Javascript, AJAX

First, I’ll create the script on my computer. To do this, I’ll need a MySQL database with some sample data. Then, I’ll connect it to the AJAX form.

  • Database host: localhost
  • Database name: autocomplete (or anything you would like to use)
  • Table name: Search
  • Database user: root

Ready to Build Your Live Search Box?

Experience easy deployment and management of your PHP, MySQL, and AJAX-powered live search box on Cloudways hosting.

Configure Apache and MySQL

Open XAMPP and Start Apache and MySQL.

Now open the URL, localhost:8080/phpmyadmin (8080 is the port on my system; yours can be different). Click on New.

Create a database called autocomplete (or anything you would like to call it).

Copy and paste the following query to create the Table (search) and column names (ID, Name) and then insert dummy data.

CREATE TABLE search (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
Name VARCHAR(30) NOT NULL
);
INSERT INTO `search` VALUES
(1, 'David Copperfield'),
(2, 'Ricky Ponting'),
(3, 'Cristiano Ronaldo'),
(4, 'Lionel Messi'),
(5, 'Shane Watson');

The following is the output of the query:

Setting up the Development Environment

To create the search engine, we need to create five files in the htdocs folder.

  1. The first file is Search.php, which is the main file where users input data and view results.
  2. The second file is db.php, which contains the database connection details.
  3. The third file is Ajax.php, which generates AJAX requests to the server and returns results.
  4. The fourth file is script.js, which contains JavaScript functions for performing AJAX requests.
  5. Finally, the fifth file is style.css, which contains the styling for the search engine.

Step 1: Create the Main File (Search.php)

This is the main file of the search engine, where the user inputs data and views the result. Create a file named search.php and paste the following code in it:

<!DOCTYPE html>
<html>
<head>
  <title>Live Search using AJAX</title>
  <!-- Including jQuery is required. -->

  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
  <!-- Including our scripting file. -->
  <script type="text/javascript" src="script.js"></script>
  <!-- Including CSS file. -->
  <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<!-- Search box. -->
  <input type="text" id="search" placeholder="Search" />
  <br>
  <b>Ex: </b><i>David, Ricky, Ronaldo, Messi, Watson, Robot</i>
  <br />
  <!-- Suggestions will be displayed in below div. -->
  <div id="display"></div>
</body>
</html>

Step 2: Create the Database Connection File (db.php)

This file contains the database connection details. Create a file named db.php and paste the following code in it:

<?php
//Database connection.
$con = MySQLi_connect(
  "localhost", //Server host name.

  "root", //Database username.

  "", //Database password.
  "autocomplete" //Database name or anything you would like to call it.
);
//Check connection
if (MySQLi_connect_errno()) {
  echo "Failed to connect to MySQL: " . MySQLi_connect_error();
}
?>

Step 3: Create the AJAX Request File (Ajax.php)

This is the main file that generates AJAX requests for the server and returns the results. Create a file named ajax.php, and paste the following code in it:

<?php
//Including Database configuration file.
include "db.php";
//Getting value of "search" variable from "script.js".
if (isset($_POST['search'])) {
//Search box value assigning to $Name variable.
  $Name = $_POST['search'];
//Search query.
  $Query = "SELECT Name FROM search WHERE Name LIKE '%$Name%' LIMIT 5";
//Query execution
  $ExecQuery = MySQLi_query($con, $Query);
//Creating unordered list to display result.
  echo '
<ul>
  ';
 //Fetching result from database.
  while ($Result = MySQLi_fetch_array($ExecQuery)) {
      ?>
  <!-- Creating unordered list items.
       Calling javascript function named as "fill" found in "script.js" file.
       By passing fetched result as parameter. -->
  <li onclick='fill("<?php echo $Result['Name']; ?>")'>
  <a>
  <!-- Assigning searched result in "Search box" in "search.php" file. -->
      <?php echo $Result['Name']; ?>
  </li></a>
  <!-- Below php code is just for closing parenthesis. Don't be confused. -->
  <?php
}}
?>
</ul>

Step 4: Create the JavaScript Functions File (script.js)

This file contains the Javascript functions that perform AJAX requests. Create a file named scripts.js and paste the following code into it:

//Getting value from "ajax.php".
function fill(Value) {
 //Assigning value to "search" div in "search.php" file.
  $('#search').val(Value);
 //Hiding "display" div in "search.php" file.
  $('#display').hide();
}
$(document).ready(function() {
 //On pressing a key on "Search box" in "search.php" file. This function will be called.
  $("#search").keyup(function() {
     //Assigning search box value to javascript variable named as "name".
      var name = $('#search').val();
     //Validating, if "name" is empty.
      if (name == "") {
         //Assigning empty value to "display" div in "search.php" file.
          $("#display").html("");
      }
     //If name is not empty.
      else {
         //AJAX is called.
          $.ajax({
             //AJAX type is "Post".
              type: "POST",
             //Data will be sent to "ajax.php".
              url: "ajax.php",
             //Data, that will be sent to "ajax.php".
              data: {
                 //Assigning value of "name" into "search" variable.
                  search: name
              },
             //If result found, this funtion will be called.
              success: function(html) {
                 //Assigning result to "display" div in "search.php" file.
                  $("#display").html(html).show();
              }
          });
      }
  });
});

Step 5: Create the Styling File (style.css)

This file contains the styling elements for the search engine. Create a file named style.css and paste the following code into it:

a:hover {
  cursor: pointer;
  background-color: yellow;
}

Testing the Live Search Box

The live search is now ready to try. To do this, open search.php by typing this address in your browser: localhost:8080/search.php

Next, press CTRL+F and input some text that will be searched in the database.

As you type your search, it will send the text to script.js. This will then send the request to ajax.php. In ajax.php, a function called fill() will send the results back. This function will also show the results in the display div on the search.php page.

That’s it!

Summary

When users can see search results as they type, it makes your website more interactive and dynamic. A live search box not only makes it better for users but also improves how your website works overall.

By using jQuery for front-end AJAX, PHP for server-side processing, and MySQL for database management, you can easily make a search feature that works well with modern web development standards.

Q: How does Live Search Works?

A: When users are typing, the live search shows suggestions on how to complete the keyword. It might be enough to enter one character for the box to autocomplete.

Q: Why is it called Live Search?

A: One of the most convenient ways to search for specific data is the AJAX search box. It is also called live search because it reacts to the users’ input in runtime.

Q: Why choose Live Search over traditional Search Box?

A: A lot of users prefer live searches to traditional ones because of its speed and useful suggestions.

What is AJAX live search?

A) AJAX live search is a feature that shows real-time search results as users type, using AJAX to fetch and display data from the server without refreshing the page.

How to create a live search in PHP?

A) Creating a live search in PHP involves using AJAX to send user input to a server-side PHP script, which then queries a database for matching results and sends them back to the browser.
Here’s a step-by-step guide:

Create the Front-End (HTML and JavaScript):

<input type="text" id="search" placeholder="Search here...">
<div id="results"></div>

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

Write the Back-End PHP Script (search.php)

<?php
$conn = new mysqli('localhost', 'username', 'password', 'database');

if ($conn->connect_error) {
    die('Connection failed: ' . $conn->connect_error);
}

if (isset($_GET['q'])) {
    $q = $conn->real_escape_string($_GET['q']);
    $sql = "SELECT * FROM products WHERE name LIKE '%$q%'";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            echo "<p>" . $row['name'] . "</p>";
        }
    } else {
        echo "No results found.";
    }
}
?>

Share your opinion in the comment section. COMMENT NOW

Share This Article

Shahzeb Ahmed

Shahzeb is a Digital Marketer with a Software Engineering background, works as a Community Manager — PHP Community at Cloudways. He is growth ambitious and aims to learn & share information about PHP & Laravel Development through practice and experimentation. He loves to travel and explore new ideas whenever he finds time. Get in touch with him at [email protected]

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Want to Experience the Cloudways Platform in Its Full Glory?

Take a FREE guided tour of Cloudways and see for yourself how easily you can manage your server & apps on the leading cloud-hosting platform.

Start my tour