Building an Instant Search (Live Search) Feature Using PHP, MySQL, and jQuery

Building an Instant Search (Live Search) Feature Using PHP, MySQL, and jQuery

Building an Instant Search (Live Search) Feature Using PHP, MySQL, and jQuery
9 min read

Instant search (live search) is a feature that lets users see search results right as they type a keyword, without having to press a submit button or reload the page. This feature gives a better user experience and looks more interactive. In this tutorial, we will build an instant search feature using PHP, MySQL, and jQuery.

Step 1: Preparing the Database

First, we need a MySQL database to store the data to be searched. Create the following database and table:

CREATE DATABASE tutorial_live_search;
USE tutorial_live_search;

CREATE TABLE produk (
    id INT AUTO_INCREMENT PRIMARY KEY,
    nama_produk VARCHAR(255) NOT NULL,
    deskripsi TEXT
);

Then, add some sample data:

INSERT INTO produk (nama_produk, deskripsi) VALUES
('Lenovo Laptop', 'Laptop with an i5 processor and 8GB RAM.'),
('Samsung Smartphone', 'Smartphone with a 6.5-inch screen and 128GB capacity.'),
('Sony Headphones', 'Headphones with high sound quality and noise-canceling features.'),
('Apple Tablet', 'Tablet with a retina display and 64GB storage.'),
('Huawei Smartwatch', 'Smart watch with fitness tracking and notification features.');

Step 2: Creating the Search View in HTML

Next, we create a simple search form using HTML. This form will contain an input for typing the keyword to search for.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Live Search with PHP, MySQL, and jQuery</title>
    <style>
        /* Simple styling for the search results */
        .hasil-pencarian {
            margin-top: 10px;
            border: 1px solid #ddd;
            padding: 10px;
            background-color: #f9f9f9;
        }
        .hasil-item {
            padding: 5px 0;
            border-bottom: 1px solid #ccc;
        }
    </style>
</head>
<body>

<h1>Product Search</h1>
<input type="text" id="kataKunci" placeholder="Search products...">
<div id="hasilPencarian" class="hasil-pencarian"></div>

<!-- jQuery Library -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="script.js"></script>
</body>
</html>

In the example above, we have an input element for typing the keyword and a <div> with the id hasilPencarian that will display the search results.

Step 3: Creating the PHP File for the Search Process

We create the file pencarian.php, which will handle the search request from JavaScript and return the results in HTML format.

<?php
// Connect to the database
$conn = new mysqli("localhost", "root", "", "tutorial_live_search");

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

$kataKunci = $_POST['kataKunci'];
$query = "SELECT * FROM produk WHERE nama_produk LIKE '%$kataKunci%' OR deskripsi LIKE '%$kataKunci%'";
$result = $conn->query($query);

if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        echo "<div class='hasil-item'><strong>" . $row['nama_produk'] . "</strong><br>" . $row['deskripsi'] . "</div>";
    }
} else {
    echo "<div class='hasil-item'>No results found.</div>";
}

$conn->close();
?>

In this file:

  • We receive the keyword from the input sent by JavaScript.
  • We use a LIKE query to match the keyword against the data in the nama_produk or deskripsi column.
  • If results are found, we display them in HTML format.

Step 4: Adding the jQuery Function to Send Data to PHP

We add a JavaScript file script.js to handle user input and send the search request to the server using AJAX.

$(document).ready(function(){
    $("#kataKunci").on("keyup", function() {
        let kataKunci = $(this).val();
        if (kataKunci.length > 2) { // Minimum 3 characters
            $.ajax({
                url: "pencarian.php",
                method: "POST",
                data: { kataKunci: kataKunci },
                success: function(data) {
                    $("#hasilPencarian").html(data);
                }
            });
        } else {
            $("#hasilPencarian").html("");
        }
    });
});

In this script.js:

  • We use the keyup event on the #kataKunci input to catch every change as the user types.
  • If the keyword is longer than two characters, we send the data to pencarian.php using AJAX with the POST method.
  • If there are results, we display them inside <div id="hasilPencarian">.

Step 5: Running and Testing the Application

Now, try opening the HTML file and typing a keyword in the search box. The search results will appear below the input instantly, without needing to reload the page.

Conclusion

By combining PHP, MySQL, and jQuery, we can build a lightweight and user-friendly instant search feature. This technique can also be applied to other projects such as searching for products, articles, or user data in various web-based applications.

Recommended for you