This blog has moved here:
Wednesday, March 12, 2008

PHP components: Autosuggest

A PHP component ready to use to implement basic autosuggest feature.

After several requests I published this simple "PHP component", ready to use, to implement a search form with an autosuggest feature using PHP and MySQL. For all Ajax beginners this is the most simple way to implement it (just with 8Kb) and the only thing you have to do is modify some parameters. Take a look at this post for all related information.

Download Autosuggest PHP component

Before starting...
Before starting, take a look at content of package:

In detail:
- autosuggest.php include a form to search something into your database.
- ajax_framework.js enables ajax functionalities
- search.php contains a standard query to looking for something into some DB table
- config.php includes DB connection parameters
Ok. Now?

Step 1: include autosuggest.php
Create a new PHP page (for example index.php) in the same folder (don't change it, ok?) where is autosuggest.php:

Open index.php and include autosuggest.php where you want into the <body> tag:

<?php include('autosuggest.php')?> this way you include the search form into your page.

Step 2: modify config.php
Change MySQL connection parameters in config.php:

Step 3: modify query parameters
In search.php you have to modify some query parameters. Not fear, is very simple.
For example, image you use your autosuggest to find all books of a certain author and your database has a table (BOOK) with two attributes book_title, and book_author. What do you have to do?
At line 23 you'll cange "USER" with the table you have, "BOOK" and at line 24 "name" with book_author:

At line 43 change "NAME" with the attribute you want in output, in this case wih book_title.

Nothing else!

CSS customizing
If you want you can change the look of each autosuggest element modifying the CSS code into autosuggest.php:

Download and test the component. If you have some problems tell me all you want.

Download Autosuggest PHP component

blog comments powered by Disqus
Josep Viciana said...


A question...
Which program you use to write the code highlighted?

Thx! Awesome blog! : )

Mike Robinson said...

Pretty cool little package!

@josep: It looks like he uses Dreamweaver.

Antonio said...

@josep & @mike: yes, it's dreamweaver (MAC version) ;)))

Cayo Medeiros aka. yogodoshi said...

I was looking for a script just like that but written in classic ASP, do you know any? I couldn't find it anywhere! =/


Alexandre said...

Thank you for this post... lite & easy to use..
Have a nive day..

Anonymous said...

Hi, excelent work
I want to ask, how to change charset of the output. Iam using another charset in database (latin2) and i cannot change it.Default charset of the ajax is utf-8. Any idea?
Thanks for answer

Anonymous said...

hello...div id="search-wrap"
in this div tag you use id="search-wrap". where is this "search-wrap" source? or why use this "search-wrap" as id .

Whizkid said...

Very nice and light implementation of Auto Suggest ! How can I add more functionality to this? I would like to navigate through the results using keyboard arrow keys. Is that possible?

markos said...


How can I add the functionality so that I can use arrows (up/down) and when I click on autosuggestion (or hit enter) it will be automatically inserted into box? Thanks!

Regards, mark

mfdesigns said...

How can you create multiple search request from $SQL_WHERE function? For instance, I would like to type the CITY, OR ZIP to get query results for either.

Ronald said...

mfdesigns, check the MySQL manual for fulltext search.

On a different note, I find using a mySQL search that uses multiple search strings very useful!

For instance, considering this moronic example list:
- green apple
- red bean
- black pear

searching for "re a" will return the first 2 rows, as they both contain the string "re" and "a". Typing "re an" will only return the second one.

FYI the SQL code:

$searchq = strip_tags($_GET['q']);

$searchword = explode(" ", $searchq);

for( $i = 0; $i < sizeof($searchword); $i++ ){
$searchword[$i] = "($SQL_WHERE) LIKE '%" .$searchword[$i]. "%'";

$queryselect = implode(" AND ", $searchword);

$getRecord_sql = "SELECT * FROM ($SQL_FROM) WHERE ($queryselect)";

Hope this is useful to others, hope this makes sense too!


Justin said...

I know someone else asked this, but I wasn't clear on the answer. If I wanted to have two search options, for instance: one option is to search by last name, and the other option is a search of a users city - how would I offer this using this script? Thanks. I love it as it works now, however!

hotmonitor said...

all is ok. but after select result isnot in text area maybe # problem I dont know

jackyw said...

great piece of code, only problem is when you shorten your drop down list you cannot select with the mouse, any idea how to resolve this.


Onnay Okheng said...

It's great...

pandi said...

it very easy to implement, but how to natigate through down/up arrow please urgent

vicky said...

Great !

but it has one drawback as arrows keys are not working , please help me or send code to make them workable, needed urgently.


Anonymous said...

Very very Nice!

did you have experience with other charsets ? like iso-8995-1 (for example 'ü Ä Ä ß'? How can i get this work ?!

TY! said...


I want to use something like this in a create form.

Eg. For looking for a city. And I want to save the city_id in the db.

Is it possible

marina said...


I've the same problem as anonymous, If someone search a word like ramón, the search fails.

I think is the way that is calling the url, if i can "translate" the word to a browser url code i think it should.

Anybody have a way to do that??


marina said...

Answering myself, the solution to ISO characters is putting this line before de code that get the results:


The function would be like this:

function autosuggest() {
q = document.getElementById('search-q').value;
// Set te random number to add to URL request
nocache = Math.random();
q=escape(q);'get', '../php/includes/search.php?q='+q+'&nocache = '+nocache);
http.onreadystatechange = autosuggestReply;
} said...

hi.. today i will implement it for my client... thanks for this...

thrasher said...

It's a quality work I'm thankful for

Silent Guy said...

Whats the use of this code when you can't even select the result with arrow keys or mouse???

Useless for me, need to search another one!!!

By the way, its a good piece of work :)

Anonymous said...

i just want that when person is filling some thing it auto suggest and when use arrow keys and enter it fills in text box. but this component go for search
help me


Alex said...

Hello Very nice script. I tried many completion script but this one is very fast and efficient BUT I've a probleme : when I click onto a result word, it's impossible to get it i the text form.
Please have you got a solution, I tried many things but !!! I can't do it by myself

web designer,web design India said...

Thanks u r information

Mayo said...

If u want to fill up textbox, use this function in ajax_framework.js:

function fill(i) {


and in search.php script put onClick function after a href="#" like this:

onClick="fill();" and between brackets write php code echo $row['NAME'];

guif said...

is it possible to detect which item is "clicked" into the autosuggest?

Anonymous said...

I tried to include the autosuggest.php page into a smarty template by using the following code:


the textbox shows but when i type, it gives "object expected" error. Thank you in advance for you help

steve said...

Good work man, thanks :)

Only one thing please,
how can we set LIMIT of suggested words.
for example 10 words...

irunbackwards said...

amazing and easy to incorporate, thanks for a great plugin!

Chris said...


Try changing $getRecord_sql to something like:

'SELECT * FROM '.$SQL_FROM.' WHERE '.$SQL_WHERE.' LIKE "'.$searchq.'%" LIMIT 10';

Star said...


I've tried using Mayo's comment to make it complete the searched word by clicking on the result but it didn't work.

any more idea's or do I have to search for another solution?

Star said...

Ok I've managed to resolve the issue here is the complete solution

To fill up the box and clear the results:

If you include "autosuggest.php" and open "autosuggest.php" file and add actual form attributes.

If you copied the values from "autosuggest.php" so simply add form attributes before your search box. My code assumes you've left the text box name as "search-q".

for more information about html form attributes visit:

Add the following to "ajax_framework.js":

function fill(i) {;

in "search.php"

edit the 'href="#"...' to
href="#" onClick="fill('Your php echo result');return false;">Your php echo result

Anonymous said...

I would also be looking for more functionality with this.

1. The ability to back fill the text box with the selected auto complete
2. both mouse and keyboard interaction
3. Having the auto suggest box hover over the original page not re shape it.

Mike said...

Great script. My question is: if I want it to auto search two totally different tables, can I?

For example, I've got one table with movie titles in it, and another with cast members in it.

If I want to execute one query to search the reviews table for the title, and another query to search the cast table for first or last name, can I do that?

And if I can, how can I output different results.

For example, the movie results would should $title, and the cast results would show $first_name and $last_name.

Any suggestions?

Teksonic said...

@ Star

Two things.
Could you give a little more information on how to implement this change of yours please.
Dreamweaver throws an error in regards to this line. Even after changing the "YourFormName" to the form info from autosuggest.php file.;

Homebound said...

Great package!
Regarding mouse selection and filling search box, Star's solution almost worked for me.

But I had to write the fill function as follows in ajax_framework.js to get it to work:
function fill(i) {
e = document.getElementById('search-q');
Hope this helps: My other changes we same as Star had outlined
1. Adding a Form attribute to the autosuggest.php with a form name
2. Adding onClick to the search.php

Anonymous said...

Just to clear things up a little

onClick="fill('php echo $row['Name']; ');return false;">

the php echo $row['Name']; part needs to be wrapped in php tags just like the php echo code that follows it

The $row[Name] will be whatever you changed your sql search to.

function fill(i) {

e = document.getElementById('search-q');


dicaprio79 said...

Hi there again,
never mind on my previous post, but how do you scroll up/down?

Thanks in advance

Dave said...

Thanks for this! I just have one question. When using an iphone, the auto suggest is always one letter behind what is being inputted. If one letter is entered, it will show null. If TA is entered, it will only show results for T, not TA until something else is typed after TA. Any ideas? Thanks!

Anonymous said...

--Just a small a contribution--

To prevent the users browser from overlaying its own autocomplete box add autocomplete="off" to the input field like so:

input name="search-q" id="search-q" type="text" autocomplete="off" onkeyup="javascript:autosuggest()"

Hemant said...

Thanks a lot.....Its awesome...

Anonymous said...

Hello! (I'm french sory for my english)

This script is very great! Thank you...

But how to see the answer ? I would like to research on the "title" for example and then when i click on this "title", a new page comes with the result..

In the AUTOSUGGEST.php :

< div id="results" >

Empty : normal ???

< / div>

In the search.php

how do you display the result on another page ?

Thank for your help! bye

Charz said...

hey it's a really helpful tutorial.Thanks :)

jimmer said...

Did anyone manage to solve the problem with not being able to use the mouse to scroll down through the results?

Great little app, nice work Antonio.

Agnieszka said...

Hi, great script :) but does anyone know how to add events for keyboard up/down arrows? Thx in advance

Anonymous said...

Also looking for a way to key up and down results.

Dimon said...

Hey Folks!
Knows anyone, how to use this autosuggestbox for several Form-fields??
Thanks for Help! ;-)

Anonymous said...

This is really great! Good job man! but there is a little problem. I can't retrieve UTF-8 elements from my MYSQL base.

Do you have any suggestions?

Imran said...

nice - how can i use it with two or more fields?

Radja said...

Cool, Man!

Simple, but your codes describes the basic working of this ajax application better than some others I found out there. I am enlightened.

Thanks from me in Jakarta.

Rollins said...

Excellent stuff. It's much easier to configure than the rest I've found.

I had a little problems though. Nothing happens when I click on the items in the drop down list.


BUU said...

Please.. I can't download the PHP components: Autosuggest... please check the link....


nivosh said...

can't use it with hebrew charecters, just english.

hebrew charecters dont return data

Miami_T said...

For UTF-8 character set you have to add following line in config.php after mysql_select_db($db_name);

mysql_query('SET NAMES utf8');

Koba said...

Good job buddy! but I think there is a problem. After I tested this script I found out that it multiples results in Opera and doesn't work in FF without hitting the Enter... I don't know what's wrong with it...

Martijn said...

Any change you could add a small script that makes it possible to select the results with the downkey?

Nicholas said...

How do I get rid of the plus signs (+) in all the data that was fetched? Some reason all the spaces were replaced by the plus signs.

  • Twitter Follow woork on Twitter
  • RSS Feed Subscribe to stay up to date
  • Podcast Coming soon...
  • 0 delicious lovers save
Support this blog with a micro subscription
If you like this blog you can contribute with a micro subscription via PayPal.
Share your links. Do you want to suggest any interesting link about web design or tech news? Submit your link.
Submit a News
Web Templates
Stock Vectors