One of the most popular features of any database driven site is probably a search functionality that allows visitors to search for information within the website. I have written a small article how to implement such a functionality using PHP/MySQL enhanced with Jquery. As you type in the search box , an asynchronous request will be made to query the database and displayed to the user .Below is a screenshot of the search system, an online demo of the application , and the download link for the full source code including the database sql .Type any of these keywords in the online : “Jquery” , “javascript”,”download” for results to be displayed .
View Demo || Download full source code
Overview
This is how the System works :
- A user clicks into the text box,the default text “Begin Typing to Search” will disappear. This effect has been done using Jquery Watermark Plug in .
- An Ajax call will be triggered and passed to the file “ajax-search.php” only if the user type a minimum of 4 Characters.
- During this Asynchronous search ,an animated loading image will be displayed in the right side of the text box.
- Finally if there is atleast one match in the database , it will be displayed in a “div” on the page .
Creating Our Database
I have created a small database that contains a topic title and a topic description .The search system will allow us to search in these 2 fields.
Below is the SQL code to create the table and add some data to it .
CREATE TABLE IF NOT EXISTS `topics` ( `topicid` int(5) NOT NULL AUTO_INCREMENT, `topictitle` varchar(200) NOT NULL, `topicdescription` varchar(500) NOT NULL, PRIMARY KEY (`topicid`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ; INSERT INTO `topics` (`topicid`, `topictitle`, `topicdescription`) VALUES (1, 'What is jquery ?', 'jQuery is a lightweight cross-browser JavaScript library that emphasizes interaction between JavaScript and HTML. It was released in January 2006 at BarCamp NYC by John Resig. Used by over 27% of the 10,000 most visited websites, jQuery is the most popular JavaScript library in use today.'), (2, 'What is javascript', 'JavaScript is an object-oriented scripting language used to enable programmatic access to computational objects within a host environment. Although also used in other applications, it is primarily used in the form of client-side JavaScript, implemented as part of a web browser, providing enhanced user interfaces and dynamic websites. JavaScript is a dialect of the ECMAScript standard and is characterized as a dynamic, weakly typed, prototype-based language with first-class functions. JavaScript '), (3, 'Where to download Jquery ?', 'You can download this javascript framework at jquery.com ?'), (4, 'How can i develop jquery Plug in ?', 'Well, First of all you need a working brain !');
Create the Form
For the sake of simplicity, I will omit the CSS design part of the search system. Since the Search is done “live” as soon as the user starts typing, a submit button will obviously not be required. Below is the HTML part of text field:
<input name="query" type="text" id="faq_search_input" />
Creating our Database Connection
Filename : database_connection.php
I will create a Database connection file separately that contains username password, host, and Database name.
You should change this info if you want to test this script on your own server.
/*Define constant to connect to database */
DEFINE('DATABASE_USER', 'root');
DEFINE('DATABASE_PASSWORD', '');
DEFINE('DATABASE_HOST', 'localhost');
DEFINE('DATABASE_NAME', 'programming');
// Make the connection:
$dbc = @mysqli_connect(DATABASE_HOST, DATABASE_USER, DATABASE_PASSWORD,
DATABASE_NAME);
if (!$dbc) {
trigger_error('Could not connect to MySQL: ' . mysqli_connect_error());
}
Code to handle the search query
Filename : ajax-search.php
When a user will type in the search box ,an ajax call will be made to this file via GET and the result will be displayed to the user .
include_once ('database_connection.php');//Including our DB Connection file
if(isset($_GET['keyword'])){//IF the url contains the parameter "keyword"
$keyword = trim($_GET['keyword']) ;//Remove any extra space
$keyword = mysqli_real_escape_string($dbc, $keyword);//Some validation
$query = "select topictitle,topicdescription from topics where topictitle like '%$keyword%' or topicdescription like '%$keyword%'";
//The SQL Query that will search for the word typed by the user .
$result = mysqli_query($dbc,$query);//Run the Query
if($result){//If query successfull
if(mysqli_affected_rows($dbc)!=0){//and if atleast one record is found
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){ //Display the record
echo '<p> <b>'.$row['topictitle'].'</b> '.$row['topicdescription'].'</p>' ;
}
}else {
echo 'No Results for :"'.$_GET['keyword'].'"';//No Match found in the Database
}
}
}else {
echo 'Parameter Missing in the URL';//If URL is invalid
}
Using Jquery to make the Asynchronous request
Filename : index.php
This is probably the “meat” of this tutorial .
To make the default text “Begin Typing to Search..” to disappear , i have used the Watermark plug .After downloading the plug in , include the plug in the header section of your page .
<script type="text/javascript" src="js/jquery.watermark.js"></script>
The rest of the code below handles the Ajax submission and displaying the results on the page .
$("#faq_search_input").keyup(function()
{
var faq_search_input = $(this).val();
var dataString = 'keyword='+ faq_search_input;
The code above will capture the data entered by the user and save in the variable faq_search_input .This will be triggered only when the user type into the textbox .The variable datastring prepared the data in the correct format to be passed in the url .
http://example.org/ajax-search.php?keyword=Jquery
The code below will Pass the input data only if is it longer than 3 characters. Before making the request , the class name “loading” will be added to the input field . This will cause an animation loading image to be added .If the ajax request is successfull ,the server response returned by ajax-search.php will be displaced within the <div id=”searchresultdata”></div> .The css “loading” class previously added to the dom is now removed .This will cause the animated loading image to become static . ( The animated and static are 2 different image actually ) .
if(faq_search_input.length>3)
//If length of input field greater than 3
{
$.ajax({//Make the ajax call using GET
type: "GET",
url: "ajax-search.php",
data: dataString,//The data to pass to the file
beforeSend: function() {
$('input#faq_search_input').addClass('loading');
//Code responsible for the animated loaded image
},
success: function(server_response)
{//If successfull ,output server response in div
$('#searchresultdata').html(server_response).show();
//Show the result on the page
$('span#faq_category_title').html(faq_search_input);
if ($('input#faq_search_input').hasClass("loading")) {
$("input#faq_search_input").removeClass("loading");
} //And finally remove the animated loading image to make it static .
}
});
}return false;
});
});
Feel free to modify the code the way you want .If you have any question or need help , do no hesitate to drop a comment below . I hope you enjoyed this tutorial .I did my best to explain the code in this article .
Related Posts
- Username Availability Check in Registration Form using Jquery/PHP
- Auto Load Page content every X second using Jquery
- An Alternative to Pagination : Facebook and Twitter Style
- Creating Message boxes using css with fadein Effects using jquery
- Remove data in a div after successfully deleted using Jquery






{ 1 trackback }
{ 35 comments… read them below or add one }
very nice article . I love the effect ! I have created a similar turorial here :
http://www.codeforest.net/simple-search-with-php-jquery-and-mysql
great post as usual!
Hi!
I’m trying to run your code on MAMP on my home development environment… and when I type, nothing happens. I created the database and everything. I don’t think it’s connecting though, since I don’t get an error whether or not it connects…
Any idea what might be going on? I love the way you put this together btw, I just need to get it working and then it will be perfect! :)
Thanks,
Nathalie
Hello Nathalie ,
Did you download the source code from the download link above ?
If yes ,Did you dump the .sql ( db.sql file ) file from the downloaded source code ?
if yes, have you edited the database_connection.php file to change the database connection information there ?
Also,type word that is found in the database so that you get results .The words should be atleast 4 characters . let me how if you have been able to solve it !
Hey – just got it to work! It seems that when I edited the “query” part I forgot to add a closing “‘” and that meant it was returning nothing. Thanks so much for your help, and for putting this code out there, I’m super grateful! :)
It makes me happy that you find that article useful Nathalie ! I got one more reason to continue blogging .. hehe :)
Hi Hyder,
I am very impressed with your demo, but what if I wanted to show result only when my typing is finished instead of show it as it goes on….. cos if I start typing a series or a serial number it will show all, but I need only matched serial only. or will it work like that if I change query like this.
/* $query = “select topictitle,topicdescription from topics where topictitle like ‘%$keyword%’ or topicdescription ==$keyword’”;
*/
Thanks alot
Sorry.. I have to change both, I think
/* $query = “select topictitle,topicdescription from topics where topictitle ==$keyword’ or topicdescription ==$keyword’”;
*/
Hi Zulian ,if you want to show the results ONLY after you have finished typing everything , then it would be preferable not to use Ajax to fetch the results . Instead , use a simple submit button .
Also , even if you haven’t typed the word fully ,after typing the 4th character ,each character typed after that would make an ajax request .So at the end , your search results will narrow down . Let me know if i have answered your question fully .
Hi Hyder,
Thanks for the quick reply. But my primary goal is to use Ajax for stopping page refreshing, so ajax is very important, but when you said 4th character, I am thinking of another option, can we change the character count to extend it?
Also I will love to see a script which can be use to insert, update, and delete data from my sql, with image upload and resize using jquery.
Thanks for the great tutorials.
Zulian
1) For the character count , Look for this code and modify it accordingly :
if(faq_search_input.length>3) {
2) For the page refresh ,i’m assuming that instead of refreshing the page “manually” , you want to refresh the page every x seconds via ajax automatically ?If yes , this article might interest you :
http://youhack.me/2010/04/13/auto-load-page-content-every-x-second-using-jquery/
And for the Data Deleting via ajax , you may consider reading this article :
http://youhack.me/2010/03/26/remove-data-in-a-div-after-successfully-deleted-using-jquery/
hope this helps ! I’ll probably write an article how to edit an article via ajax soon :)
Hi!
Thanks for the reply…. Please consider a complete CRUD script with image upload and resize.
Pretty nice post. I just stumbled upon your blog and wanted to say that I have really enjoyed browsing your blog posts. In any case I’ll be subscribing to your feed and I hope you write again soon!
Hi..
I watched a video from youtube.com and made a script as it shoed, but mine is not working. can you please find the error and correct it for me. the two file are below.
search.html
function getStates(value) {
$.post(“getStates.php”,{partialState:value},function(data)
$(“#results”).html(data); // dreamweaver says there is a syntax error on line 7 but I canot figure it out.
});
}
//getStates.php
<?php
mysql_connect("localhost","root","12345") or die(mysql_error());
mysql_select_db("tripconcept") or die(mysql_error());
$partialState = $_POST['partialState'];
$states = mysql_query("SELECT states FROM countries WHERE state like '%$partialStates%'");
while ($state = mysql_fetch_array($states)) {
echo "”.$sate['country'].”";
}
?>
Thank you in advance.
sorry.. I think my search.html below.
function getStates(value) {
$.post(“getStates.php”,{partialState:value},function(data)
$(“#results”).html(data); // dreamweaver says there is a syntax error on line 7 but I canot figure it out.
});
}
Hi.. I am sorry, I think I cannot write scripts here, please can you email me your mail address, I will send it to you via email.
I also need to put one more div tag after results tag, which will display default data, but when user start searching, and if he get any matched text, the default tag should be hidden before showing results tag.
Regards
Zulian
Zulian email me the complete file at ismaakeel(at) gmail.com
Hi Hyder,
Thanks for the reply, I found the error, and it was a typing mistake. instead of state, I typed “sate”. now it is working fine.
I will email you an idea on which you can help me.
Thanks
Zulian
Hey Zulian
I saw that same tutorial on youtube and ive got the same syntax problem you have, how did you fix it? can you email me your code? that would be sweet!
@Fx : what’s wrong with your code ?
Nice one…
Would you mind to include script $_POST for ajax ? thx before
@Yuta:
In the PHP Code Find :
and replace it by :
In the Jquery Code , Find
and replace it by :
That’s all . it should be working fine after that .
Hey how would you add a link to a site like google and Yahoo’s search engine does? Like if I wanted to display a link to the articles when the search is displayed
@Chris :
Make the Title in the results a hyperlink that will point to another page,let’s say :
result.php .
The Result page url should look like this :
result.php?id=1
result.php?id=2
result.php?id=3
Then on result.php , capture the value of this id via $_GET ,and make a query for this id in the database .
If you have no idea what im talking about , i would recommend you to learn how the global variable $_GET works . Hope this helps !
So does this script search the web, or just the website you want it too?
I’m looking for a script that searches Yahoo and Google and bring’s it all together?
Any ideas would be great, thanks :)
Thanks man .. really nice script … well done and works smooth :)
Here an example what’s possible with this script:
http://www.buenavidarealtors.com/test/ajaxsearch.php – (just a test script for the moment)
Test words: Beach, Merida, House
@Daniel : Good Work man ! it really fits in there .. :)
Please, can you help me to do hyperlinkeable the title of the results???????
it is very necessary for my page.
thanks very much for this!!!
Great article.
Would be good to “not” show dropdown search suggestions ( based on browser history ) as you type, as this messes this code and look up. Is there a fix for this ?
@daniel, great implementation.
I would like, to see a selection tick box with this, to compartmentalise results.
So prior to typing you choose:
a)fruit b)places c)people ( this is example by the way.
Then if you select say FRUIT, and begin typing A , the results are shown say starting at apple, just for fruit.
Be interested to get some feedback on doing this please
@ Blue : to turn off the type suggestion based on browser history ,add this html attribute to the text field .
Hi Hyder, thanks a lot for the tutorial, ive been searching and trying out many php jquery ajax mysql searches, but havent been able to find or adapt one of the ones ive found to my needs
I need the search to query the database in different columns, not just in one, for example to type “pizza dominos” and find all the records that match “pizza” in one column and ” dominos” in another
thanks again for the tutorial in the first place :)
I was wondering if your script was able to do that in its current form, or if its adaptable to do it, ive been trying to do it with with this one by adding either fulltext search and/or by using explode to split up the keywords, but I don´t know that much php and havent had much success
http://www.9lessons.info/2009/06/autosuggestion-with-jquery-ajax-and-php.html
@Pedro : There’s nothing much you have to change in the code in order to do that . All you have to do is to formulate your sql query properly .what problem are you getting with the explode() function actually ? paste fragment of your code , i might help you :)
my main problem is that i have no idea how to explode a keyword and then create queries from it, ive tried reading books on the matter but they lose me at some point or another,
heres the code im using ( i adapted it from the 9lessons tutorial, but if you prefer i can work with your tutorial code )
<?php
include('config.php');
if($_POST)
{
$q=$_POST['searchword'];
$sql_res=mysql_query("SELECT * FROM test_user_data WHERE ( fname like '%$q%' or lname like '%$q%' or type like '%$q%' ) order by fname ASC LIMIT 4");
while($row=mysql_fetch_array($sql_res))
{
$fname=$row['fname'];
$lname=$row['lname'];
$type=$row['type'];
$img=$row['img'];
$country=$row['country'];
$address=$row['address'];
// this is meant to get the # of rows found for the query, however it does not
$num_rows = mysql_numrows($sql_res);
// maybe i can use explode to split the lines and create several querys, but how?
$q2=explode(" ", $q);
$re_fname='‘.$q.’‘;
$re_lname=’‘.$q.’‘;
$re_type=’‘.$q.’‘;
$final_fname = str_ireplace($q, $re_fname, $fname);
$final_lname = str_ireplace($q, $re_lname, $lname);
$final_type = str_ireplace($q, $re_type, $type);
// how can I make the output capitalize every first letter of the word? using ucfirst or ucwords, but how?
$name = ucfirst($final_fname);
?>
<img src="user_img/” style=”width:100px; height:43px; float:left; margin-right:6px” />
<?php echo "” . $final_lname; ?>
<?php echo "” . $address; ?>
<?php echo " Ver mas resultados de $fname
Mostrando los primeros $result resultados”;?>
——-
its on http://www.thebaroom.com/hambre2/ and its been driving me crazy for weeks!
Dude , you have wrongly used the explode() function .
$q=$_POST['searchword'];
$q2=explode(” “, $q);
echo $q2[0] ; //It will display the first word
echo $q2[1] ; //second
echo $q2[2] ; //third ..
thanks for the help, it really means a lot to me, I dont know many php gurus, and Ive posted on many sites looking for help with this
It might be too much to ask, but how could I go about making the query search for each exploded part in the different columns?
if the person typed “pizza phoenix”
it would be $q2[0] = “pizza” and $q2[1] = “phoenix”
but im not sure how to go about the sql to search for both of those in the various columns, im looking for php courses in my area to be able to know this ( and more ) but any help would be highly appreciated