- Ajax Live Search With PHP and MySQL
- Learn how To Integrate Live Search In PHP And MySQL With JQuery :
- PHP Example — AJAX Live Search
- AJAX Live Search
- Example Explained — The HTML Page
- The PHP File
- Build Live Search Box Using PHP, MySQL and AJAX.
- Stop Wasting Time on Servers
- Database Details
- Database Setup
- Setup Files
- Create Search Form and Related Files
- search.php
- db.php
- ajax.php
- scripts.js
- style.css
- Host PHP Websites with Ease [Starts at $10 Credit]
- Q: How does Live Search Works?
- Q: Why is it called Live Search?
- Q: Why choose Live Search over traditional Search Box?
- Share This Article
- “Cloudways hosting has one of the best customer service and hosting speed”
- Shahroze Nawaz
Ajax Live Search With PHP and MySQL
Today, In this tutorial we are going to discuss how to create php ajax live search box using MySQL database. Now a days every website has integrated this kind of search feature. This search box populate the results in real time from MySQL database based on entered text in search box.
We have implemented this ajax live search box demo using php pdo connection. When user enter any text in search box and click on search button, Then it will send the request to «controller.php» page, with the help of ajax call and display the realtime search result in «search.php» page. Check out our blog archive on the topic if you’re looking to learn about Ajax Search Box in PHP, MySQL and JQuery.
Learn how To Integrate Live Search In PHP And MySQL With JQuery :
CREATE TABLE `post` ( `POSTID` int(3) NOT NULL, `POSTTITLE` varchar(100) NOT NULL, `POSTDETAILS` varchar(10000) NOT NULL, `POSTLINK` varchar(100) NOT NULL )
Once You have created above table, Then put the records in this table.
config.php
Consists of database configuration details to establish database connection.
php /* DATABASE CONFIGURATION */ define('DB_SERVER', 'localhost'); define('DB_DATABASE', 'skptricksdemo'); define('DB_USERNAME', 'root'); define('DB_PASSWORD', ''); ?>
controller.php
Controller work is to control the flow of execution. Here when user click on search button, JQuery script send request to «controller.php» page and it will process the request and return response to be displayed.
php include("DAO.php"); if(isset($_POST["search-data"])) $searchVal = trim($_POST["search-data"]); $dao = new DAO(); echo $dao->searchData($searchVal); > ?>
DAO.php
This DAO class helps to establish the database connection and populate/fetch the records from MySQL database on AJAX call using JQuery.
php include("config.php"); class DAO public function dbConnect() $dbhost = DB_SERVER; // set the hostname $dbname = DB_DATABASE ; // set the database name $dbuser = DB_USERNAME ; // set the mysql username $dbpass = DB_PASSWORD; // set the mysql password try $dbConnection = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass); $dbConnection->exec("set names utf8"); $dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); return $dbConnection; > catch (PDOException $e) echo 'Connection failed: ' . $e->getMessage(); > > public function searchData($searchVal) try $dbConnection = $this->dbConnect(); $stmt = $dbConnection->prepare("SELECT * FROM `post` WHERE `POSTTITLE` like :searchVal"); $val = "%$searchVal%"; $stmt->bindParam(':searchVal', $val , PDO::PARAM_STR); $stmt->execute(); $Count = $stmt->rowCount(); //echo " Total Records Count : $Count .
" ; $result ="" ; if ($Count > 0) while($data=$stmt->fetch(PDO::FETCH_ASSOC)) $result = $result .'.$data['POSTLINK'].'">'.$data['POSTTITLE'].' '; > return $result ; > > catch (PDOException $e) echo 'Connection failed: ' . $e->getMessage(); > > > ?>
search.php
This page consists of Jquery, AJAX, PHP and HTML code, which helps to fetch records form MySQL database when user enter any text in search box and click on search box.
- JQuery script helps to detect entered text in search box, when user click on search box.
- AJAX Code helps to fetch records from database and display the result in «search.php» page without page refresh.
src="jquery-3.2.1.min.js"> #search-data padding: 10px; border: solid 1px #BDC7D8; margin-bottom: 20px; display: inline; width: 80%; > .search-result border-bottom:solid 1px #BDC7D8; padding:10px; font-family:Times New Roman; font-size: 20px;color:blue; > #display-button position:relative; width:80px; height:38px; float:right; left:-55px; text-align:center; float:right; left:-55px; background-color:#4683ea; > // on click search results. $(document).on("click", "#display-button" , function() var value = $("#search-data").val(); if (value.length != 0) //alert(99933); searchData(value); > else $('#search-result-container').hide(); > >); // This function helps to send the request to retrieve data from mysql database. function searchData(val) $('#search-result-container').show(); $('#search-result-container').html(' Please Wait. '); $.post('controller.php','search-data': val>, function(data) if(data != "") $('#search-result-container').html(data); else $('#search-result-container').html("No Result Found. "); >).fail(function(xhr, ajaxOptions, thrownError) //any errors? alert(thrownError); //alert with HTTP error >); > style="width: 700px;margin:40px auto;"> id="search-box-container" > > How To Integrate Live Search In PHP And MySQL With JQuery :
type="text" id="search-data" name="searchData" placeholder="Search By Post Title (word length should be greater than 3) . " autocomplete="off" /> id="display-button" style=""> style="padding:7px;" src="search.png" /> id="search-result-container" style="border:solid 1px #BDC7D8;display:none; ">
This is all about ajax live search box demo using php pdo connection. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.
PHP Example — AJAX Live Search
AJAX can be used to create more user-friendly and interactive searches.
AJAX Live Search
The following example will demonstrate a live search, where you get search results while you type.
Live search has many benefits compared to traditional searching:
- Results are shown as you type
- Results narrow as you continue typing
- If results become too narrow, remove characters to see a broader result
Search for a W3Schools page in the input field below:
The results in the example above are found in an XML file (links.xml). To make this example small and simple, only six results are available.
Example Explained — The HTML Page
When a user types a character in the input field above, the function «showResult()» is executed. The function is triggered by the «onkeyup» event:
If the input field is empty (str.length==0), the function clears the content of the livesearch placeholder and exits the function.
If the input field is not empty, the showResult() function executes the following:
- Create an XMLHttpRequest object
- Create the function to be executed when the server response is ready
- Send the request off to a file on the server
- Notice that a parameter (q) is added to the URL (with the content of the input field)
The PHP File
The page on the server called by the JavaScript above is a PHP file called «livesearch.php».
The source code in «livesearch.php» searches an XML file for titles matching the search string and returns the result:
//get the q parameter from URL
$q=$_GET[«q»];
// Set output to «no suggestion» if no hint was found
// or to the correct values
if ($hint==»») $response=»no suggestion»;
> else $response=$hint;
>
//output the response
echo $response;
?>
If there is any text sent from the JavaScript (strlen($q) > 0), the following happens:
- Load an XML file into a new XML DOM object
- Loop through all elements to find matches from the text sent from the JavaScript
- Sets the correct url and title in the «$response» variable. If more than one match is found, all matches are added to the variable
- If no matches are found, the $response variable is set to «no suggestion»
Build Live Search Box Using PHP, MySQL and AJAX.
AJAX search refers to live search functionality, where the search engine starts to display results as you type characters in the input box. It allows you to see search results without having to load a display page. Ajax search thus makes it easier and faster for users to find what they are looking for. AJAX search is developed with JavaScript (jQuery), MySQL PHP, and AJAX.
This is how Google implements this idea on its search pages:
Live search is an essential aspect of UI and user experience on the website. In this article, I will highlight the process of building an autocomplete (Live Search) engine for your website.
- Code editor (Sublime or Notepad++ are good options)
- Apache and MySQL (either XAMPP or WAMP). In this article, I will use XAMPP.
- HTML, CSS, PHP, MySQL, Javascript, AJAX.
I will first build the script on my local machine. For this, I will need a MySQL database with sample data and connect it with the AJAX form.
Stop Wasting Time on Servers
Cloudways handle server management for you so you can focus on creating great apps and keeping your clients happy.
Database Details
Here are the details of my sample database:
Database name: autocomplete (or anything you would like to use)
Database Setup
Open XAMPP and Start Apache and MySQL.
Now open the URL, localhost:8080/phpmyadmin (8080 is the port on my system; yours can be different)
PHP Hosting: Best PHP 7 & PHP 5.6 Web Hosting
Create a database called “autocomplete” (or anything you would like to call it).
Copy and paste the following query to create the Table (search), Column names (Id, Name), and then insert dummy data.
CREATE TABLE search ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, Name VARCHAR(30) NOT NULL ); INSERT INTO `search` VALUES (1, 'David Copperfield'), (2, 'Ricky Ponting'), (3, 'Cristiano Ronaldo'), (4, 'Lionel Messi'), (5, 'Shane Watson');
The following is the output of the query:
Setup Files
Create the following files in htdocs folder (usually found in C:/xampp/htdocs)
Search.php (This is the main file of the search engine, where a user inputs data and views result).
db.php (This file contains database connection details).
Ajax.php (The main file that generates AJAX request to the server and returns results).
script.js (This file contains javascript functions to perform AJAX requests).
style.css ( Contains styling for the search engine).
Create Search Form and Related Files
In this step, I will create the following files:
search.php
This is the main file of the search engine, where the user inputs data and views the result. Create a file named search.php and paste the following code in it:
Ex: David, Ricky, Ronaldo, Messi, Watson, Robot
db.php
This file contains the database connection details. Create a file named db.php and paste the following code in it:
ajax.php
This is the main file that generates AJAX request for the server and returns the results. Create a file named ajax.php, and paste the following code in it:
scripts.js
This file contains the Javascript functions that perform AJAX requests. Create a file named scripts.js and paste the following code in it:
//Getting value from "ajax.php". function fill(Value) < //Assigning value to "search" div in "search.php" file. $('#search').val(Value); //Hiding "display" div in "search.php" file. $('#display').hide(); >$(document).ready(function() < //On pressing a key on "Search box" in "search.php" file. This function will be called. $("#search").keyup(function() < //Assigning search box value to javascript variable named as "name". var name = $('#search').val(); //Validating, if "name" is empty. if (name == "") < //Assigning empty value to "display" div in "search.php" file. $("#display").html(""); >//If name is not empty. else < //AJAX is called. $.ajax(< //AJAX type is "Post". type: "POST", //Data will be sent to "ajax.php". url: "ajax.php", //Data, that will be sent to "ajax.php". data: < //Assigning value of "name" into "search" variable. search: name >, //If result found, this funtion will be called. success: function(html) < //Assigning result to "display" div in "search.php" file. $("#display").html(html).show(); >>); > >); >);
style.css
This file contains the styling elements for the search engine. Create a file named style.css and paste the following code in it:
The search engine is now ready for testing. For this carry out the following steps:
First, open search.php by typing the following URL in the browser:
Next, input some text that will be searched in the database.
Notice that as you type in your query, it will pass the text to script.js that will forward this request to ajax.php file. In the ajax.php, a javascript function named “fill()” will pass the fetched results. This function will also display the result(s) into the “display” div in the “search.php” file.
This is it. The Live Search box for your website is now ready to be deployed on any PHP Host for real-world traffic. If you need help with the code or would like to suggest improvements, do leave a comment below.
Host PHP Websites with Ease [Starts at $10 Credit]
Q: How does Live Search Works?
A: When users are typing, the live search shows suggestions on how to complete the keyword. It might be enough to enter one character for the box to autocomplete.
Q: Why is it called Live Search?
A: One of the most convenient ways to search for specific data is the AJAX search box. It is also called live search because it reacts to the users’ input in runtime.
Q: Why choose Live Search over traditional Search Box?
A: A lot of users prefer live searches to traditional ones because of its speed and useful suggestions.
Share This Article
Customer Review at
“Cloudways hosting has one of the best customer service and hosting speed”
Sanjit C [Website Developer]
Shahroze Nawaz
Shahroze is a PHP Community Manager at Cloudways — A Managed PHP Hosting Platform. Besides his work life, he loves movies and travelling.