- Live search in PHP and MySQL with AJAX
- What is inside?
- Popular live search plugins and libraries
- About this example
- Database script
- Application configuration
- Rendering data list from database using MySQL
- jQuery AJAX script to request live search
- Code mechanism for live search in PHP
- Output: Live search in PHP
- Conclusion
- Comments to “Live search in PHP and MySQL with AJAX”
- Быстрый поиск с выводом результатов
- Форма
- Стили формы поиска и результатов:
- PHP: Динамический поиск с использованием PHP, MySQL и AJAX
- Создание динамического поиска с использованием PHP, MySQL и AJAX
- 1. Создайте файл подключения к базе данных.
- 2. Создайте поисковую форму ajax.
- 3. Создайте скрипт PHP для поиска в БД.
Live search in PHP and MySQL with AJAX
Live search is a handy feature for filtering data that enriches the user experience. It helps to shortlist the result based on the criteria selected by the end-user.
Search feature implementation effort is based on the complexity of the search requirement of the application. Also, it varies depends on the application need and structure.
The below list of items shows the types of search mechanisms commonly used by the applications.
- Single common filter to search multiple columns.
- Dedicated column-wise search filters.
- Range filters with a range of dates, performance, estimates and more.
- Google-like advanced search filter.
In this modern web/mobile application era, applications’ enriched interface made the search easy for the end-user. The design enrichment increases the usability of the search with the features like auto-complete, keyword-highlight and more.
What is inside?
Popular live search plugins and libraries
There are popular plugins available to integrate a search feature for an application.
DataTables – jQuery Javascript library has a seamless search feature. Only thing is that this plugin not only provides the search but also many like sort, pagination, inline-editing.
In a previous article, I have created code to enable Datatables column search with server-side processing.
Another alternative solution to enable search is the AJAX-enabled live search library.
Having more choices online, my preference is to go with a custom code for most of the application functionalities. Since the libraries may turn to be overload, minimalism will save effort during the maintenance.
About this example
This is to create a live search in PHP to filter database results. It lets the users enter the keyword, based on which the search is going to happen.
This example will display a single input field above the list of data from the database. The keyword search is applied to all the database columns to find a match.
I thought it would be better to highlight the search keyword along with the filtered result. But, it’s a configurable feature only.
This live search example also displays paginated results. The search criteria will be kept alive during the pagination. The results count per page is from the application config.
It uses PDO to connect the MySQL database to fetch results during the search and the pagination.
The following screenshot shows the file structure of this example.
Database script
This database script includes the CREATE statement, PRIMARY KEY, AUTO-INCREMENT specification with the data dump.
Import this script before running this example. It helps to try the live search on the dynamic data.
CREATE TABLE IF NOT EXISTS `posts` ( `id` int(8) NOT NULL, `post_title` varchar(255) NOT NULL, `description` text NOT NULL, `post_at` date DEFAULT NULL ) ENGINE=InnoDB AUTO_INCREMENT=18 DEFAULT CHARSET=latin1; -- -- Dumping data for table `posts` -- INSERT INTO `posts` (`id`, `post_title`, `description`, `post_at`) VALUES (1, 'Plugin integration', 'Documentation to help to integrate plugins.', '2021-03-02'), (2, 'Learning languages', 'Guide to get started learning new languages.', '2021-03-25'), (3, 'Editor tools', 'Number of tools and utilities available in the editor.', '2021-03-25'); -- -- Indexes for dumped tables ALTER TABLE `posts` ADD PRIMARY KEY (`id`); ALTER TABLE `posts` MODIFY `id` int(8) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=18;
Application configuration
This is a basic configuration created for this code. It has the constants to define the units per page and a directive to enable or disable an optional feature of the live search functionality.
This code sets the ENABLE_HIGHLIGHT value to boolean true. And so, it highlights the keywords among the filtered result.
Rendering data list from database using MySQL
This is a landing page that displays the dynamic data with a live search option.
It includes the PHP code to query the database and retrieve the results to be listed in a tabular format.
On submitting the search form, it calls AJAX to get the filtered result from the server.
It also includes a pagination option to move back and forth. The pagination request is also sent via the AJAX call to show a seamless data display.
$searchModel = new SearchModel(); $row_count = $searchModel->getCount(); $limit = " limit " . $start . "," . Config::LIMIT_PER_PAGE; if (! empty($row_count)) < $per_page_html .= ""; $page_count = ceil($row_count / Config::LIMIT_PER_PAGE); if ($page_count > 1) < for ($i = 1; $i '; > else < $per_page_html .= ''; > > > $per_page_html .= ""; > $result = $searchModel->getAllPosts($start, Config::LIMIT_PER_PAGE); ?> .img-url