I'm moving to a new blog. A blog that's all about my adventures as a traveling designer and wonder seeker.

This tutorial is about building a live search with PHP and jQuery. It has a couple of bits and pieces to make it work. First of all we will design the form and port it to HTML and CSS. After that we will write up the jQuery to make everything work and a PHP file that will take care of generating the results. We will also look at a couple of possible bugs that can become security risks or just make the user experience worse.

This tutorial requires beginner knowledge of HTML, CSS, jQuery and PHP + MySQL. Let's start!

Concept

Let's lay this one out. We need an input, we need some JavaScript that will take the value of the input and post it to our search.php file, and that one gives us our results in a nice and formatted output. To make the search live we will need to do a couple of things. First let's look at the visual part.

Design

So we are going to make a really simple design for this. Just an input box, with a results output area and a title. That's it, very simple and effective:

HTML

Very simple HTML markup, nothing fancy or unfamiliar. One thing I will point out is the autocompletion parameter on the input field. This just disables the input's default drop-down with previous searches.

<!-- Main Title -->
<div class="icon"></div>
<h1 class="title">Live Search Tutorial</h1>
<h5 class="title">(searches through PHP functions and shows them on php.net)</h5>
<input id="search" type="text" />
<h4 id="results-text">Showing results for: <strong id="search-string">Array</strong></h4>
<h3>jQuery</h3>

Ok, so you made it to here, this is where the "magic" happens. This is where we submit our search query and get data from our search.php file back. Let's make this work first. In the root folder of the tutorial create a search.php file that contains only this:

<!--?php echo('Hello World!'); ?-->

Now in the custom.js file we will add the first function, the icon focus effect, really straightforward. When you click the magnifying glass icon the input gets focused:

// Icon Click Focus
$('div.icon').click(function(){
    $('input#search').focus();
});

The next thing is going to be the input submit function. Because this is a live search it needs to output data on the fly, so if we think about it, we want data to be sent every time a user presses a key on his keyboard, or let's rather say after the user presses it. So we will bind the event to the "key up" event. Every time a user lifts his finger off of his keyboard the function will submit the search query to the search.php file.

This is the jQuery submit function:

$("input#search").live("keyup", function(e) {

    // Set Search String
    var search_string = $(this).val();

    // Do Search
    if(search_string !== ''){
        $.ajax({
            type: "POST",
            url: "search.php",
            data: { query: search_string },
            cache: false,
            success: function(html){
                $("ul#results").html(html);
            }
        });
    }return false;
});

This does exactly what we want it to do: it takes the value of the input and sends it to our search.php file after a "key up" is detected. This reveals a bug: if you type too fast the function won't successfully get the last search query. It is a pretty annoying bug so let's get rid of it by wrapping the search functionality in a JavaScript function and triggering it with a 100ms timeout after a "key up". That will take care of our little bug.

Here is the search function:

// On Search Submit and Get Results
function search() {
    var query_value = $('input#search').val();
    $('b#search-string').text(query_value);
    if(query_value !== ''){
        $.ajax({
            type: "POST",
            url: "search.php",
            data: { query: query_value },
            cache: false,
            success: function(html){
                $("ul#results").html(html);
            }
        });
    }return false;
}

When we call this, it will take the input value and submit it to the search.php, but let's wrap it in a timeout. And let's add another check: if the input is empty, do nothing.

$("input#search").live("keyup", function(e) {
    // Set Timeout
    clearTimeout($.data(this, 'timer'));

    // Set Search String
    var search_string = $(this).val();

    // Do Search
    if (search_string == '') {
        // Do nothing
    }else{
        $(this).data('timer', setTimeout(search, 100));
    };
});

Ok, now that we have that part finished, let's fade in and fade out the results only when we have something to show. For this we set the results text and the container for the results to display none in CSS and we can fade them in with jQuery when we get some results from the query.

Updated function:

$("input#search").live("keyup", function(e) {
    // Set Timeout
    clearTimeout($.data(this, 'timer'));

    // Set Search String
    var search_string = $(this).val();

    // Do Search
    if (search_string == '') {
        $("ul#results").fadeOut();
        $('h4#results-text').fadeOut();
    }else{
        $("ul#results").fadeIn();
        $('h4#results-text').fadeIn();
        $(this).data('timer', setTimeout(search, 100));
    };
});

This means we are done with jQuery, now let's move on to the logic of the tutorial, the PHP.

PHP

The first thing we need to do is a MySQL connection. In this tutorial I will be using the MySQLi class instead of PDO just because I like using it more for simpler stuff. Do a bit of your own research, but how you get and store data is entirely up to you, this is just my way of doing it.

So let's connect to our MySQL DB:

// Credentials
$dbhost = "localhost";
$dbname = "tutorial";
$dbuser = "username";
$dbpass = "password";

// Connection
global $tutorial_db;

$tutorial_db = new mysqli();
$tutorial_db->connect($dbhost, $dbuser, $dbpass, $dbname);
$tutorial_db->set_charset("utf8");

// Check Connection
if ($tutorial_db->connect_errno) {
    printf("Connect failed: %sn", $tutorial_db->connect_error);
    exit();
}

Here we just define the parameters for the connection like the host, user and so on. Then we make the connection and in case it fails we just print out the error and exit the script. Pretty straightforward.

Let's move on to the second part of this script, our HTML output. I have a certain way of doing it. I store the HTML format for each result in a variable and put in placeholders, so when I want to change things I just go in and change the HTML once and it changes for the entire script. It's easy to make changes and updates to it.

// Define Output HTML Formatting
$html = '';
$html .= '<ul><li class="result">';
$html .= '<a href="urlString" target="_blank">';
$html .= '</a><h3>nameString</h3>';
$html .= '<h4>functionString</h4>';
$html .= '</li>';
$html .= '</ul>';

So we have that now, and you can clearly see the placeholders, the urlString, nameString and functionString. We will replace those with their actual values for each result.

Now let's get our search string from the Ajax function we made previously. The important thing to mind here is a couple of security measures. First we will escape the string so we prevent SQL injection, and then strip out any funky characters, because our search is simple and you can only search for alphanumeric functions, so we only need those characters. Everything else will be replaced with a space. (Note: for testing you can change the $POST to $GET and test the script by just opening it up and appending a URL parameter to it, so you would do - search.php?query=Array).

// Get Search
$search_string = preg_replace("/[^A-Za-z0-9]/", " ", $_POST['query']);
$search_string = $tutorial_db->real_escape_string($search_string);

The next thing we will do is a simple if statement that checks if the query string is longer or equal than one character. Additionally, we want to make sure that it's not a single whitespace:

// Check Length More Than One Character
if (strlen($search_string) >= 1 && $search_string !== ' ') {
}

What this avoids is important!

When people try to do ugly things to your site they can put a % in your live search and that will spit out all results from the database. Or, if you use a single whitespace, it can match to everything with a whitespace. So what happens here is we avoid the searching of special characters with our preg replace function that strips every non alphanumeric character and replaces it with a space. But think about it, if someone enters % as the only character we just replaced that with a whitespace and that's just as bad. So in the if statement we just say that the string needs to be more then one character and can't be a whitespace. That's it!

Now let's do the search and output the results. First, we will take our search string and get any results from the database where the function name or function syntax matches our search query. Then we will loop through the results and put them into an array. After that we just loop through the resulting array and print the array to the screen. In case the results array is empty we will return a "No results" message instead. Let's take a look at the function:

// Build Query
$query = 'SELECT * FROM search 
WHERE function 
LIKE "%'.$search_string.'%" 
OR name LIKE "%'.$search_string.'%"';

// Do Search
$result = $tutorial_db->query($query);
while($results = $result->fetch_array()) {
    $result_array[] = $results;
}

// Check If We Have Results
if (isset($result_array)) {
    foreach ($result_array as $result) {
        // Output
        print_r($result);
    }
}else{
    // Output
    echo('Nothing to display.');
}

Now let's take a look at how we output the correct HTML code for each result. We have the HTML in a variable and now we just run it through a string replace function that PHP already has ready for us.

// Format No Results Output
$output = str_replace('urlString', 'JavaScript:void(0);', $html);
$output = str_replace('nameString', 'No Results Found.', $output);
$output = str_replace('functionString', 'Sorry :(', $output);

// Output
echo($output);

So we just made our no results output, now let's make the output for the actual query result.

// Format Output Strings
$display_function =$result['function'];
$display_name = $result['name'];
$display_url = 'http://php.net/manual-lookup.php?pattern='.urlencode($result['function']).'&lang=en';

// Insert Name
$output = str_replace('nameString', $display_name, $html);

// Insert Function
$output = str_replace('functionString', $display_function, $output);

// Insert URL
$output = str_replace('urlString', $display_url, $output);

// Output
echo($output);

This happens in each loop of the results array, so we store the appropriate parts of the result in variables and make the final outgoing URL. A new window will open when one of our results gets clicked. It's pretty simple, PHP.net gives us a placeholder for the search string, and we just need to URL-encode the string and specify the language.

Let's move on to highlighting the results.

In order to make this pretty let's highlight the parts of the result where it matches our search query. We are going to use preg_replace for this.

$display_name = preg_replace("/".$search_string."/i", "<strong class="highlight">".$search_string."</strong>", $result['name']);

What we do here is search the resulting function name for our search query and then, if we find it, we replace it with our search query wrapped in bold tags with the class for highlighting. So we can style those in CSS easily. We need to do the same for the actual function string and that's it. You might notice we have an i in the first parameter of preg_replace, that just ignores case sensitivity. So we don't need to search for Array to get Array, it will match it to array also.

The last thing I want to show you is how I got the functions for the search.

// Compile Functions Array
$functions = get_defined_functions();
$functions = $functions['internal'];

// Loop, Format and Insert
foreach ($functions as $function) {
    $function_name = str_replace("_", " ", $function);
    $function_name = ucwords($function_name);

    $query = '';
    $query = 'INSERT INTO search SET id = "", function = "'.$function.'", name = "'.$function_name.'"';

    $tutorial_db->query($query);
}

I just got the defined functions list in PHP with the getdefinedfunctions() function and then looped through them. For the names I just replaced the "_" in function names with a space and uppercased the words. Neat!

Pretty simple tutorial but still a long one! I really hope you learned something new, I will say that this is my approach to this, I know there can be a million others, but this works best for me. You can make this a lot better with some more work and add a ton of cool features to it. The next one I would add would be a popularity index next to results, so you would +1 the popularity index each time a result gets searched for, and that gives you the option of sorting the results by popularity.

Thanks for going through this and I hope you liked it!

Live Preview

Download Files

Join The Discussion (101 Comments)

Submit Comment
avatar

s.m.r Samadi

That's awesome! I can easily add image and some other html tags inside the code, Thank you.

Posted 3 months ago
avatar

sujit kumar

Nice info about<a href="http://nareshit.in/php-training/"> Php </a> it’s reallyhelpful…. If it possible share some more tutorials……….

Posted 3 months ago
avatar

Sebastian

replace jquery 'live' function after jquery 1.8 with 'on' : $("input#search").live("keyup", function(e) { : : $("input#search").on("keyup", function(e) { :

Posted 1 year ago
avatar

clivend

many thanks!

Posted 1 year ago
avatar

zack

How is this connected to the database table? I am trying to follow along with this. I am getting it connected to the server but no results are showing up :/ I am hoping I have just named my table header differently? thanks, Zack

Posted 1 year ago
avatar

munir

hello, how can I uncode the arabic chars in the mysql database?? the below code doesn't work: $query = 'SELECT * FROM search WHERE function LIKE "%'.mysql_real_escape_string(utf8_decode($search_string)).'%"'; thanks for your help!

Posted 1 year ago
avatar

md sawkat hossain

very nice Serch

Posted 2 years ago
avatar

md sawkat hossain

very nice Serch

Posted 2 years ago
avatar

Mark

I'm new in PHP, but does your code needs to be revise somehow or is it already a running program? I've always get an error with my wampserver 2.5 whenever I type in the search box and it can't connect to the database.

Posted 2 years ago
avatar

Cred

This is great demo. Really learned quite a bit from this. Thank you. Trying to do more with it: How can I display the Results of clicking on one of the Search Results, below the search bar? The content of the Results will be from MySQL database, on the same row as the selected Search Result. For e.g. suppose I wanted to display the URL of the selected item below the Search bar (after the user selects the Search Result), instead of going to the URL.

Posted 2 years ago
avatar

Fio

How can I show the full data before showing the results from the search?

Posted 2 years ago
avatar

Dan Francis

This is a reasonably nice demo on how to achieve the ajax search functionality. It would be better though, to see this working using PHP PDO, and with some options on how to set it up to search specific DB tables/areas.

Posted 2 years ago
avatar

SDFGHJ

SDFGHJKDFGHJ

Posted 2 years ago
avatar

henry

thanks for his tutorial really helpful i also viewed another live search with ajax on TalkersCode.com which i found very useful to create a good search system http://talkerscode.com/webtricks/basic-instant-fulltext-search-system-using-ajax-and-php.php

Posted 2 years ago
avatar

LekkerLogic

This is awesome and helped me big on a recent project. I have extended this to use a Bootstrap table and count how many times a query occurs for anyone who might be interested. http://lekkerlogic.com/2015/01/php-mysql-ajax-live-data-table-search-tutorial/

Posted 2 years ago
avatar

Download CS 1.6

Nice script. Thankyou

Posted 2 years ago
avatar

Julius

Great work sir Zan, can you teach us also how to display the profile within page for example name John and it will display the name, address, sex and age within same page from database sql. Thank you sir Zan

Posted 3 years ago
avatar

Sales

Hi there and thanks alot for e very good tutorial, it works fine, but i have a problem that the rest of my site is running jquery 2.1.3 so i cant use the tutorial.. do you knoq how diccult it is to make 2.1 combtible? Best Regards

Posted 3 years ago
avatar

Adrian

Which line(s) of code should have to change to search for asian string?

Posted 3 years ago
avatar

Raimehn Roger

Your example is so brillant. Thank you

Posted 3 years ago
avatar

Mark Jovic

Your example is so brilliant.. Very Helpful to my project.. Thank You so much..

Posted 3 years ago
avatar

Raqib

Very Helpful!!

Posted 3 years ago
avatar

Andrew

Loving this, its a really nice script. One thing though, could you give me some pointers as to change it from a "live search" to more of a "autocomplete" thing? ie, I want to be able to press enter or click on one of the results to literally just put that in that text window, rather than be a search results script. any tips much appreciated. thanks again

Posted 3 years ago
avatar

Ameed

Hello .. Thanks a lot i have a problem when i uploaded the code on live server it doesn't work . any help please

Posted 3 years ago
avatar

Ugu

Thank you very much for this good code. Would be awesome if you could integrate pagination as well. Could you please help on this ? Regards and thx again.

Posted 3 years ago
avatar

Alex

Never mind, I solved it

Posted 3 years ago
avatar

Alex

When I search for something all of the content on my website duplicate. Any idea why?

Posted 3 years ago
avatar

luky

hey, thx for script. if i can have one tip for you, use shorter names of variables.. that means, istead of $output - $o, $input_string - $q, $result_array - $res, you would not believe how much is then the code shorter and more readable for eye :)

Posted 3 years ago
avatar

kaveh

thank you for your code; i have written the alike in PDO prepared statement. but I have problems would you please give a guidance on PHP using PDO?

Posted 3 years ago
avatar

walter

Uncaught TypeError: undefined is not a function ejecutarajax.js:29(anonymous function) ejecutarajax.js:29j jquery.js:2k.fireWith jquery.js:2n.extend.ready jquery.js:2I

Posted 3 years ago
avatar

Walter

well, but I think changing some feature ... changing to a class and some MVC, class.search.php, but I'm still studying the code, since not a lot of javascript is a bit complex ajax call from some classes suggestions?

Posted 3 years ago
avatar

Zan

Just tested it out and the download is fine. Check your computer for malware or viruses :)

Posted 3 years ago
avatar

cosychiruka

Files can't be downloaded, the zip file is corrupt..can you help out with that

Posted 3 years ago
avatar

Camilo Uribe

What if I just want to put the name into the searched value into the input? Hope you can help me.

Posted 3 years ago
avatar

teja

thanks very much its very helpful to my social networking site......awesome.......

Posted 3 years ago
avatar

nawapol

Why search resulty go to php.net only if will adjust search in my site, How do you do? $display_url = 'http://php.net/manual-lookup.php?pattern='.urlencode($result['function']).'&lang=en'; You can adjust search result as similar google.com and have pagination button? Please send to me if adjust already at my Email Thank you sir

Posted 4 years ago
avatar

Carsten Rønaasen

I have in fact managed to put in profile pictures in the search result based on their own unique ID from db. Did all of it in search.php with defining new html def's and a few variables.. its easy actualy. just send a mail for intructions

Posted 4 years ago
avatar

Phoebe

Files cant be downloaded. Any kind soul want to help out?

Posted 4 years ago
avatar

riemann

Hello Zan, thanks a lot for that code - as a novice in the field I used the feature to understand the fundamental basics between html, js, jq, ajax, php and the mysql backend operation - it took me two days to get that issue running - in case there is another greenhorn out there i struggled most with the mysql connection: (1) via phpmyadmin i manually set up db=tutorial, create table=search, create the rows "id", "function", "name" (2) I used the comment left by zan regarding db at the end, pasted it into a new file "insert.php" after MySQLConnect and run the script. The script grabs all the functions from php.net and store it properly in the db. What i don't understand is that the id's after import are still all "0" (INT(5)) obviously because all three rows are on primary key???. For the expats that is of course all natural but i thought for beginners i leave note.

Posted 4 years ago
avatar

Skylarker

Thanks so much for the post! What about entries that begin with a numerical value? The problem that I am having is that when I do a search for say "restaurant", "24-hour gym" appears in the search results, even though there is (obviously) no match. How to I correctly account for this?

Posted 4 years ago
avatar

Manipandiyan

Hi Nice post.This is very helpful to learn about ajax and php . And thanks once again.

Posted 4 years ago
avatar

Tasha

Hi. This is awesome, thanks so much. I got it to work on its own by typing in the path where I have the folder saved in my localhost. I would like to integrate this into my joomla website. But I don't know where I would put the code. I tried using Jumi module but it would not work.

Posted 4 years ago
avatar

Nadimuthu

Nice post.. This is very helpful to learn something about PHP ajax class library.. And thanks once again…

Posted 4 years ago
avatar

Mosaix

It's really nice share, thanks. Can you give me some free pdf to learn about ajax and php? I tried your tutorial in this post, but there is something wrong, the search doesn't give any result. Please help

Posted 4 years ago
avatar

Genov

Hi Really nice script! Thanks for the great work! I've managed to run it properly on my site but what I'm trying to do is to put a clear button in the search field. I am using this: $(document).ready(function() { $('input.search').wrap('').after($('').click(function() { $(this).prev('input').val('').focus(); })); }); It does the job but the search results are still displaying. What I want is to clear the existing results after clicking on the clear button. Could someone advice on this? I hope I didn't confuse you with my explanation! Thanks!

Posted 4 years ago
avatar

vis

Awesome Post Sir ! Thank you very much ! :-)

Posted 4 years ago
avatar

Cole

how does it rank the results?

Posted 4 years ago
avatar

Lequnia

Can we display the profile picture? with the search?

Posted 4 years ago
avatar

Jagath

Nice it working well........................

Posted 4 years ago
avatar

Ross

This is awesome. I'm just wondering, is it totally secure to put a search like this on a site? Is the database put in jeopardy by using this?

Posted 4 years ago
avatar

Teraman

Thanks for the code, this is awesome! What should I modify in jQuery to add more than one input? Thanks

Posted 4 years ago
avatar

Achyut

thanks 4 the code

Posted 4 years ago
avatar

thusitha

hi, Thanks for this live search. I've used this search and it was awsome . But I've faced a problem.In database i have record "Thusitha" and when i type “ thusitha” nothing are displayed("no result found" notification displayed ). When I type “Thusitha” everything works fine. . But when I adds your "tutorial" database and check ,it is not case sencitive. Can you give me a tip for that?

Posted 4 years ago
avatar

Marco Aurélio

Thank you.

Posted 4 years ago
avatar

lima_fil

Hi, Thanks for great engine. Working fine. For any other language you need to set Regex, like Alexis suggested in first comment. In search.php, line 44: $search_string = preg_replace(“/[^A-Za-z0-9áéíóúÁÉÍÓÚÑñ]+$/”, ” “, $_POST['query']); - Spanish $search_string = preg_replace("/[^A-Za-z0-9šŠđĐčČćĆžŽ]+$/", " ", $_POST['query']); - Serbian etc ... Does anybody know how to set match only if word start with search term?

Posted 4 years ago
avatar

capricorn

great code.......thanks...

Posted 4 years ago
avatar

richard

no me funciono malditos

Posted 4 years ago
avatar

steve

malditos no me funciono

Posted 4 years ago
avatar

haroon

Hello, Thank you for this nice serach script: I get an Parser Error in "$display_url" $display_function = preg_replace(“/”.$search_string.”/i”, ““.$search_string.”“, $result['fName']); $display_name = preg_replace(“/”.$search_string.”/i”, ““.$search_string.”“, $result['lName']); $display_url = ‘../php/genClientDetails.php?userID=’.urlencode($result['ID']); Error: Parse error: syntax error, unexpected '.' search.php on line 73 Right not iam not able to use this script, whatever i have a question. can i used for persian languages (uft8) Thanx

Posted 4 years ago
avatar

Meks

My searches are case sensitive. In database i have record John and when i type "john" nothing are displayed. When i type "John" everything works fine. Can you give me a tip for that?

Posted 4 years ago
avatar

Chris

Great code, but how do I define what happens when a result is clicked other than being redirected to a URL? I would like to stay on same page and populate empty form fields. Thanks

Posted 4 years ago
avatar

Steve

Hey, thanks for great tutorial! I edited a bit to fit it to my needs. But there is one thing I can't do... I have a DB with english and french item-names. When I search for any item (no matter if the search-term is in french or english), I want to show both, the EN and FR strings. But I don't know how I can realize it. How can I add both strings into one result? Thank you so much!

Posted 4 years ago
avatar

Praneeth

hello guys, I want to get this output into a html table. Can someone help me..?

Posted 4 years ago
avatar

Dan

Simple enough, thank you! This was very helpful!

Posted 4 years ago
avatar

sao ratha

Hi, thank for you great search from, but could i use arrow key to move up or down of result? Thanks.

Posted 4 years ago
avatar

khari

where is the entire code? In its entirety?

Posted 4 years ago
avatar

Øyvind

Aykut: Yes. Add LIMIT 0,10 to the end of the SQL query string.

Posted 4 years ago
avatar

Aykut

Hi, thanks for the awesome script. I had a question: is there a way to limit the search results? You got a whole list if for example type the letter a. Is it possible to set the search results to for example 10 results so the users are required to enter more letters? Thanks!

Posted 4 years ago
avatar

dyld

Hi, thanks for this great tutorial. I have a question about this example. Is it possible to use arrow keys for navigating records? Best regards

Posted 4 years ago
avatar

saad

the live function has been deprecated. so you can just use following syntax for keyup!... $( "#target" ).keyup(function() {

Posted 4 years ago
avatar

Ny Sokheng

Hi. This is a very nice live search. really love it. but I cannot search from my field which containing Unicode. to echo the unicode from database i usually use SET NAMES utf8 like this: $res = mysql_query("SET NAMES utf8"); $query="Select * From TABLE WHERE FIELD='STRING'" $res = mysql_query($query); Please advise where should I change the code to be able to query the search result from unicode field. Thank you...

Posted 4 years ago
avatar

Alexander Drachan

The search-engine is awsome, thank you for you work!!! Wanted to say that I had to add this into the js to make it work faster: You have to stop the queries while the text is being typed. var ajaxRequest; function search() { ajaxRequest = $.ajax({...}) } $("input#search").live("keyup", function(e) { if (search_string == '') { }else{ if (ajaxRequest) {ajaxRequest.abort();} $(this).data('timer', setTimeout(search, 100)); }; }); Hope that helps. Cheers!

Posted 4 years ago
avatar

Bradley

Hi there, This is absolutely fantastic but I am looking to adapt on it by a couple of ways. Basically, what I am trying to do is assign each search field to an ID or category so basically if the category ID was 1 then a div will display saying this is compatible. If the ID was 2 then a different div would display saying it's not compatible then if the ID was 3 then the final div would display it might be compatible with more text etc within the divs. It doesn't matter if the page was to refresh or anything like that but I am so keen to get this. If anyone can help I would really appreciate it. Thank you. Bradley

Posted 4 years ago
avatar

Jamie

Just wondering, is there a way to add auto complete to this? So you can make a sort of Username search for a private messaging system?

Posted 4 years ago
avatar

grails

thanks for the sample code. i may just tweak on the PHP side to match the framework i am using

Posted 4 years ago
avatar

Albert

$display_function = preg_replace("/".$search_string."/i", "".$search_string."", $result['fName']); FNAME IS FROM MY TABLE $display_name = preg_replace("/".$search_string."/i", "".$search_string."", $result['lName']); LNAME IS ALSO FROM MY TABLE $display_url = '../php/genClientDetails.php?userID='.urlencode($result['ID']); Replace the parameters on these lines to match those of your table and you will be fine

Posted 4 years ago
avatar

andres

Hi, I have this error Fatal error: Call to a member function fetch_array() on a non-object in /home/-------/public_html/s---o/search.php on line 54 My script work with pdo...there is a problem if I mix pdo and mysqli?? I will waiting for your answer Best regards!

Posted 4 years ago
avatar

cray

I was just wondering if there's an easy way to "clear" the search box after you click on a result. I tried to do sth like onclick="document.getElementById('search').value=''" but that obviously wouldn't work. Any suggestions?

Posted 4 years ago
avatar

Mario Praga

Thank you very much for sharing that . It Is possible also when pressing enter to search for the string inserted in the field ? ( like Amazon search ) thx

Posted 4 years ago
avatar

Manuel

Would you please let us know how to make a LIMIT for the search results that comes out from the database?! it turns out to get thousands of results and it keeps scrolling, I just need to add a MORE button and limit the scroll by 5. THANKS IN ADVANCE

Posted 4 years ago
avatar

Emmanuel cr

Hello! and to search for data in another table that is not "search", what I have to do?

Posted 4 years ago
avatar

Albert

Thank you very much for this wonderfully mouth watering piece of work. The accompanying tutorial was superb. I installed it once and it work. I adopted it for search on my clients table and it is doing just that for me. Thank you again. I was wondering if you could point me to the part of the code that allows you to click somewhere for the search result to disappear. Currently unless you clear the content of the search box. Is it possible for the results to disappear when you change focus to a different object, like click somewhere in the page? I will appreciate that thank you.

Posted 4 years ago
avatar

ringa

Hi, Thanks for the tutorial, it's really useful. How can i use arrow keys in this example? Thanks in advance.

Posted 4 years ago
avatar

Dan

This is an awesome tutorial. I have been playing around and modifying it a little, but the one thing I just can't figure out is how to make the search not take the search terms order into account. For example if I type "foo bar" it would like it to find "bar foo" and "foo boo bar". This will help when title and data in the search are inconsistent. If anyone has a nudge in the right direction on this I would be greatly appreciative. I'm guessing that maybe changing the regex, but not 100% sure the best way to implement.

Posted 4 years ago
avatar

Anders

How can I show the results in a table insted of a ul?

Posted 4 years ago
avatar

shripad

Suppose I don't want the result to have a hyperlink I just want the search box to be filled with the result then what do I do?

Posted 4 years ago
avatar

Albert

Emmanuel Cr **** Just replace the search with the table you want to search from

Posted 4 years ago
avatar

Bryan Lewis

Thank you! You saved my life with this tutorial. Integrates beautifully with an ExpressionEngine backend with very little modification.

Posted 4 years ago
avatar

viveka

thanku so much for your coding

Posted 4 years ago
avatar

Donovan

Wow this is great. Nice functionality, and highly responsive. Been looking for a solid script like this for some time. Thanks!

Posted 4 years ago
avatar

Mark

Great easy to follow code. Thanks. Would you be able to post how to add a infinite scroll or "show more" pagination to the existing code? Is there an easy way to include this in ajax code to use limits for php mysql query?

Posted 5 years ago
avatar

Sjoerd Postma

For the people who want to use jQuery 1.9+, change the following line: $("input#search").live("keyup", function(e) { to: $("input#search").on("keyup", function(e) { The search should now work under jQuery 1.9+ too. :) I've been looking around on the interwebs and found out that .live is no longer supported. So a simple adjustement was needed to make it work again. I had emailed the author about it, but I guess he's busy as I haven't received anything back from him. Anyway, here's the solution! -Sjoerd

Posted 4 years ago
avatar

Andrej

Hi Žan, I found your tutorial very usefull. ... And I have additional request :) Could you explain in sentance or two, how to modify your mysql code to use "Match against" instead of "Like" and use full text index in tables. The thing is, that when there is large amount of data in Mysql, "like" query is too slow to use. Thanks

Posted 4 years ago
avatar

Angesh

thanx guys awesome code wanted the way it is.... thanx alottt...

Posted 5 years ago
avatar

deepak

you code is awesome but when i check it for my database it is giving any result or error.... as i already change the database name , table name and search attributes of the table.......... it display blanck result..... help me out................

Posted 4 years ago
avatar

Echorde

Got it!! No problem!

Posted 4 years ago
avatar

Echorde

How do you limit the number of results that are shown?? Right now, if the table has about 1000 rows with the letter 'a', all the 1000 are being displayed slowing down the entire webpage!

Posted 4 years ago
avatar

Peter

First, you can get all keyword in a array with something like: $keywords = explode( " ", $keyword); Then you can loop this array building with a query like (you need to improve it): foreach( $keywords as $searchstring ) { $sq .= "n (function LIKE '%$searchstring%' ) AND "; } As result you will have something like (function LIKE '%tv%' ) AND (function LIKE '%plasma%' ) And this will match your result, I guess

Posted 5 years ago
avatar

Dina

THANK YOU! Lots of PHP/MySQL background, but getting my feet wet in jQuery and AJAX. This is an awesome writeup and super-helpful! Really, thank you so much for taking the time to write this all out in such a straightforward way.

Posted 4 years ago
avatar

Paddy C

Fantastic!!! Live search, ever since it really came along or people noticed it on Google has been something a lot of developers have been trying to perfect for a while and you have made it look so simple. Well done peoples :P if anything we look forward to more, great tutorials...

Posted 5 years ago
avatar

Alexis

thanks for the code :) a change the regex to match spanish caracters $search_string = preg_replace("/[^A-Za-z0-9áéíóúÁÉÍÓÚÑñ]+$/", " ", $_POST['query']); do you have issue or tips to search partial words like: if i search string like ( tv sony plasma) match ok with the title (tv sony plasma dhmi model blablabla ) but if a write (tv plama) nothing sort! best regards

Posted 5 years ago