Skip to content

Auto complete text box with PHP, jQuery and MySql

In this tutorial I would like to show you how easy to implement google like search auto complete text box with PHP, jQuery and MySql.

Let’s start the autocomplete textbox tutorial. Firstly download the autocomplete jQuery plugin and extract it to your hard drive.Copy jquery autocomplete file to your project folder. You will also need to include JQuery since autocomplete plugin depended on JQuery. you can also use below listed cdn’s.

  
  
  

Define the autocomplete function and provide the source file.


Require the following HTML.

Database table
Below is my table with some sample data . Import following SQL statement via phpMyAdmin or any other MySQL tool.


CREATE TABLE `tag` (
  `id` int(20) NOT NULL auto_increment,
  `name` varchar(50) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=11;

INSERT INTO `tag` (`id`, `name`) VALUES
(1, 'ActionScript'),
(2, 'PHP7'),
(3, 'AppleScript'),
(4, 'jquery'),
(5, 'ajax'),
(6, 'mysql'),
(7, 'wordpress'),
(8, 'Asp'),
(9, 'Ruby'),
(10, 'xml');

PHP
Create autocomplete.php and this file is called from our jquery script . we can get the textbox value by term field ($_GET[‘term’]) from the query string. Now we will fetch the data from tags table and filtering the tags by $_GET[‘term’]. At last we will return the filtered tags data in JSON format.

query("SELECT * FROM tag WHERE name LIKE '%".$searchTerm."%' ORDER BY name ASC");
    $data = [];
    while ($row = $query->fetch_assoc()) {
        $data[] = $row['name'];
    }
    
    //return json data
    echo json_encode($data);
?>
0 0 votes
Article Rating
Subscribe
Notify of
guest

1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments