Autocomplete Search Box In PHP And MySQL

Autocomplete Search Box In PHP And MySQL

Below is a step-by-step guide to implementing an autocomplete search box in PHP and MySQL with a Bootstrap design, using a sample database table named products:

  • Step 1: Set up your database
  • Step 2: Insert sample data
  • Step 3: Database Connection (connection.php)
  • Step 4: Create the HTML form with Bootstrap design (index.php)
  • Step 5: Create the PHP script to handle AJAX requests (search.php):
  • Step 6: Replace placeholders with your actual database credentials

Step 1: Set up your database:

  • Create a MySQL database named autocomplete_db.
  • Create a table named products with the following structure:
CREATE TABLE products (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255)
);

Step 2: Insert sample data:

Insert some sample data into the products table to test the autocomplete functionality:

INSERT INTO products (name) VALUES
('Product 1'),
('Product 2'),
('Product 3'),
('Product 4'),
('Product 5');

Step 3: Database Connection (connection.php)

// Database connection
$servername = "localhost";
$username = "username";
$password = "password";
$database = "autocomplete_db";

$conn = mysqli_connect($servername, $username, $password, $database);

if(!$conn){
    die("Connection failed: " . mysqli_connect_error());
}

Step 4: Create the HTML form with Bootstrap design (index.php)

  • Create an HTML form with an input field where users can type their search queries.
  • Include Bootstrap CSS for styling.
<!DOCTYPE html>
<html>
<head>
    <title>Autocomplete Search Box</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("#search").keyup(function(){
                var searchText = $(this).val();
                if(searchText != ''){
                    $.ajax({
                        url: 'search.php',
                        method: 'post',
                        data: {query:searchText},
                        success: function(response){
                            $("#show-list").html(response);
                        }
                    });
                } else {
                    $("#show-list").html('');
                }
            });
              $(document).on('click', '.list-group-item', function(){
                var selectedValue = $(this).text();
                $('#search').val(selectedValue);
                $("#show-list").html('');
            });
        });
    </script>
    <style>
        #show-list
        {
            margin-top: -1rem !important;
        }
        .list-group-item
        {
            cursor:pointer;
        }
    </style>
</head>
<body>
    <div class="container mt-5">
        <h2 class="text-center mb-4">Autocomplete Search Box</h2>
        <div class="form-group">
            <input type="text" id="search" class="form-control" placeholder="Type to search...">
        </div>
        <div id="show-list"></div>
    </div>
</body>
</html>

Step 5: Create the PHP script to handle AJAX requests (search.php):

This PHP script will receive the search query via AJAX, perform a database query, and return matching results.

<?php
include('connection.php');

$output = '';
if(isset($_POST['query'])){
    $search =  $_POST['query'];
    $query = "SELECT * FROM products WHERE name LIKE '%$search%'";
    $result = $conn->query($query);
    if(mysqli_num_rows($result) > 0){
        while($row = mysqli_fetch_assoc($result)){
            $output .= '<div class="list-group-item">' . $row['name'] . '</div>';
        }
    } else {
        $output .= '<div class="list-group-item">No results</div>';
    }
    echo $output;
}
?>

Step 6: Replace placeholders with your actual database credentials

Replace "localhost", "username", and "password" with your actual database credentials.

That's it! You've implemented an autocomplete search box using PHP, MySQL, jQuery, and AJAX with Bootstrap design, and a sample database table named products.




Mahendra Pratap Singh

Hey there! I'm a Senior Full Stack Developer with 10 +years of experience in the tech world. I've spent a lot of time working with different tools and languages, like PHP, WordPress, Laravel, and CodeIgniter... Read More >>

1 Comments

  • Sam

    8 February, 2024 09:20:51 AM

    Code Is good and work proper thanks

    • Tutorialsonweb Team

      8 February, 2024 09:21:14 AM

      Thanks Sam.

Leave a Comment