Autocomplete textbox using jQuery, PHP and MySQL


Autocomplete textbox is very user friendly for web project. In this tutorial you can learn how to implement google like search textbox in PHP. Using jQuery UI we can easily display auto suggestion from the database under textbox.

Let’s start the autocomplete textbox tutorial. Here we will display a textbox for skill entry. Once the user starting to enter skill, the autosuggestion skills would be listed under the textbox. These autosuggestion skills would be fetched from the database skills table.

jQuery UI Library & jQuery

We need to include jQuery library, jQuery UI library and jQuery UI stylesheet.

<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>

Define the autocomplete function and provide the source file.

<script>
$(function() {
    $( "#skills" ).autocomplete({
        source: 'search.php'
    });
});
</script>

HTML

Just require the following HTML.

<div class="ui-widget">
    <label for="skills">Skills: </label>
    <input id="skills">
</div>

PHP Source File

We can get the textbox value by term field ($_GET['term']) from the query string. Now we will fetch the data from skills table and filtering the skills by $_GET['term']. At last we will return the filtered skills data in JSON format.

<?php
    
//database configuration
    
$dbHost 'localhost';
    
$dbUsername 'root';
    
$dbPassword '';
    
$dbName 'codexworld';
    
    
//connect with the database
    
$db = new mysqli($dbHost,$dbUsername,$dbPassword,$dbName);
    
    
//get search term
    
$searchTerm $_GET['term'];
    
    
//get matched data from skills table
    
$query $db->query("SELECT * FROM skills WHERE skill LIKE '%".$searchTerm."%' ORDER BY skill ASC");
    while (
$row $query->fetch_assoc()) {
        
$data[] = $row['skill'];
    }
    
    
//return json data
    
echo json_encode($data);
?>

That’s all, these steps is enough for autocomplete textbox implementation in PHP.

28 Comments

  1. Ashish Said...
  2. Shurvir Mori Said...
  3. Meeaoww Said...
  4. Pravin Said...
  5. Parth Said...

Leave a reply

Connect With CodexWorld