Live Search using PHP, MySQL Database and Javascript

Live Search using PHP, MySQL Database and Javascript

Hello friends! We’re here again to discuss live search functionality in a dynamic website using php and javascript. Previously, we had a post on the search operation using only php. We recommend to go through it first, at here. Now, we’ll see as the data is typed, the suggestions will come under it. So, without wasting time, lets start how to do this.

Creating search takes 3 steps:

let us see them one by one

1. Creating Database

First things first! Lets create a Database using the following query. We are creating a table ’employee’ in which id, name, email and company name data details exists.

CREATE TABLE IF NOT EXISTS `employee` ( `id` int(11) NOT NULL, `name` varchar(255) NOT NULL, `email` varchar(100) NOT NULL, `company` varchar(100) NOT NULL )

Lets Fill some records in the table.

INSERT INTO `employee` (`id`, `name`, `email`, `company`) VALUES (1, 'Mike', 'mike@softglobe.net', 'Softglobe'), (2, 'James', 'james@gmail.com', 'Google'), (3, 'Mark', 'mark123@microsoft.com', 'Microsoft'), (4, 'Albert', 'albert29@softglobe.net', 'Softglobe'), (5, 'Smith', 'smith@nokia.com', 'Nokia'), (6, 'Robert', 'robert@tcs.com', 'TCS'), (7, 'Raffel', 'raffel@cognizant.com', 'Cognizant'), (8, 'John', 'john123@essel.com', 'Essel'), (9, 'Peter', 'peter@hp.com', 'HP'), (10, 'Barton', 'barton@apple.com', 'Apple');

2. Creating Live search using javascript

To make this tutorial short and easy, we have made a single file for our front end designing. It includes front UI, css and connection code. So create a file search-form.php and paste the following code in it.

      body < font-family: Arail, sans-serif; >/* Formatting search box */ .search-box < width: 300px; position: relative; display: inline-block; font-size: 14px; >.search-box input[type="text"] < height: 32px; padding: 5px 10px; border: 1px solid #CCCCCC; font-size: 14px; >.result < position: absolute; z-index: 999; top: 100%; left: 0; background: white; >.search-box input[type="text"], .result < width: 100%; box-sizing: border-box; >/* Formatting result items */ .result p < margin: 0; padding: 7px 10px; border: 1px solid #CCCCCC; border-top: none; cursor: pointer; >.result p:hover     

Live Search using PHP, MySQL Database and Javascript

Enter the queries to search in the search box.


An amazing tutorial on Technopoints

Make sure you have javascript files in your folder for proper working of the code. You can get them, form internet very easily. Just Google them.

We are not here using session, but you can easily implement this functionality in your session projects also.

3. Add the backend

Now, we need a special file to fetch the data from database and return it to the main file. So lets Create a file backend-search.php and add the following code in it. This is the last step to create the live search functionality.

setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); > catch(PDOException $e)< die("ERROR: Could not connect. " . $e->getMessage()); > // Attempt search query execution try< if(isset($_REQUEST['term']))< // create prepared statement $sql = "SELECT * FROM employee WHERE name LIKE :term"; $stmt = $pdo->prepare($sql); $term = $_REQUEST['term'] . '%'; // bind parameters to statement $stmt->bindParam(':term', $term); // execute the prepared statement $stmt->execute(); if($stmt->rowCount() > 0)< while($row = $stmt->fetch())< echo "

" . $row['name'] . "

"; > > else< echo "

No results found

"; > > > catch(PDOException $e)< die("ERROR: Could not able to execute $sql. " . $e->getMessage()); > // Close statement unset($stmt); // Close connection unset($pdo); ?>

In the above file, we are using a PDO connection method for connecting with the database because it is more secure and prevents SQL injections. We have used a word “LIKE” in an SQL query to fetch the related names as we type characters in the search box.

The REQUEST super global variable is used to let the system know that the fetch operation should be started as soon as the user starts typing in the text box. the suggestions appears under the text box appears within a fraction of second.

We’ve added a styling using w3.css classes. You can get it by downloading the source code. The following image is a view of a homepage of our tutorial project.
Now visit the search-form.php file, You can directly put any employee name’s starting letter, the matching phrases will be displayed automatically. Even you can insert rows in one tab and perform fetching without refreshing the page as shown below image.

Live Search using PHP, MySQL Database and Javascript

Looking nice na? Why not try it now? The source code is always available for free of cost. You can directly download it from the below link.

Источник

Ajax Live Data Search using jQuery PHP MySQL

Sometimes, you need to add live search functionality for populating data without loading the whole page. This tutorial shows you how you can implement Ajax live data search using a PHP mysql database. And you can use the free source code of ajax live data search using jquery php MySQL.

PHP Mysql and jquery Ajax live search from database example. In this tutorial, you will learn how to implement ajax search in PHP and MySQL database.

How to Create Live Search Box Using PHP MySQL and jQuery AJAX

  • First Create a Database Connection File
  • Create an ajax search form
  • Create a PHP Script for Search to DB

1. First Create a Database Connection File

In this step, you will create a file name db.php and update the below code into your file.

The below code is used to create a MySQL database connection in PHP. When we insert form data into MySQL database, there we will include this file:

2. Create an ajax search form

In this step, you need to create an ajax search form and update the below code into your ajax search form.

      
Search for users

3. Create a PHP Script for Search to DB

In this step, you need to create one file name ajax-db-search.php and update the below code into your file.

The below code is to search into a MySQL database table using an Ajax PHP script:

%' LIMIT 100"; $result = mysqli_query($conn, $query); if (mysqli_num_rows($result) > 0) < while ($user = mysqli_fetch_array($result)) < echo $user['name']."
"; > > else < echo "

User not found.

"; > > ?>

Conclusion

In this tutorial, you have learned how to implement live search in PHP with MySQL database table using PHP code.

This is a very basic and easy example of ajax search into the MySQL database using PHP code.

Источник

Build Live Search Box Using PHP, MySQL and AJAX.

live search php mysql 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.

  1. Code editor (Sublime or Notepad++ are good options)
  2. Apache and MySQL (either XAMPP or WAMP). In this article, I will use XAMPP.
  3. 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).

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.

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.

Источник

Читайте также:  Php array search return array
Оцените статью